blob: 8eec0e563f49b62739606cde8ad179ea981fa7ff [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner173234a2008-06-02 01:18:21 +000045#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000046#include "llvm/Target/TargetData.h"
47#include "llvm/Transforms/Utils/BasicBlockUtils.h"
48#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000050#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000051#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000052#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000053#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000054#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000055#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000056#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000057#include "llvm/Support/Compiler.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000058#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000059#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000060#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000061#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000062#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000063#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000064#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000065#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000066#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000067using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000068using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000069
Chris Lattner0e5f4992006-12-19 21:40:18 +000070STATISTIC(NumCombined , "Number of insts combined");
71STATISTIC(NumConstProp, "Number of constant folds");
72STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000075
Chris Lattner0e5f4992006-12-19 21:40:18 +000076namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000077 class VISIBILITY_HIDDEN InstCombiner
78 : public FunctionPass,
79 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000080 // Worklist of all of the instructions that need to be simplified.
Chris Lattner2806dff2008-08-15 04:03:01 +000081 SmallVector<Instruction*, 256> Worklist;
Chris Lattnerdbab3862007-03-02 21:28:56 +000082 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000083 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000084 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000085 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000086 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000087 InstCombiner() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000088
Owen Andersone922c022009-07-22 00:24:57 +000089 LLVMContext *Context;
90 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +000091
Chris Lattnerdbab3862007-03-02 21:28:56 +000092 /// AddToWorkList - Add the specified instruction to the worklist if it
93 /// isn't already in it.
94 void AddToWorkList(Instruction *I) {
Dan Gohman6b345ee2008-07-07 17:46:23 +000095 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerdbab3862007-03-02 21:28:56 +000096 Worklist.push_back(I);
97 }
98
99 // RemoveFromWorkList - remove I from the worklist if it exists.
100 void RemoveFromWorkList(Instruction *I) {
101 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
102 if (It == WorklistMap.end()) return; // Not in worklist.
103
104 // Don't bother moving everything down, just null out the slot.
105 Worklist[It->second] = 0;
106
107 WorklistMap.erase(It);
108 }
109
110 Instruction *RemoveOneFromWorkList() {
111 Instruction *I = Worklist.back();
112 Worklist.pop_back();
113 WorklistMap.erase(I);
114 return I;
115 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000116
Chris Lattnerdbab3862007-03-02 21:28:56 +0000117
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000118 /// AddUsersToWorkList - When an instruction is simplified, add all users of
119 /// the instruction to the work lists because they might get more simplified
120 /// now.
121 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000122 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000123 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000124 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000125 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000126 }
127
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000128 /// AddUsesToWorkList - When an instruction is simplified, add operands to
129 /// the work lists because they might get more simplified now.
130 ///
131 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000132 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
133 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000134 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000135 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000136
137 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
138 /// dead. Add all of its operands to the worklist, turning them into
139 /// undef's to reduce the number of uses of those instructions.
140 ///
141 /// Return the specified operand before it is turned into an undef.
142 ///
143 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
144 Value *R = I.getOperand(op);
145
Gabor Greif177dd3f2008-06-12 21:37:33 +0000146 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
147 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000148 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000149 // Set the operand to undef to drop the use.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000150 *i = UndefValue::get(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000151 }
152
153 return R;
154 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000155
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000156 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000157 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000158
159 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000160
Chris Lattner97e52e42002-04-28 21:27:06 +0000161 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000162 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000163 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000164 }
165
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000166 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000167
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000168 // Visitation implementation - Implement instruction combining for different
169 // instruction types. The semantics are as follows:
170 // Return Value:
171 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000172 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000173 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000174 //
Chris Lattner7e708292002-06-25 16:13:24 +0000175 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000176 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000177 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000178 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000179 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000180 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000181 Instruction *visitURem(BinaryOperator &I);
182 Instruction *visitSRem(BinaryOperator &I);
183 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000184 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000185 Instruction *commonRemTransforms(BinaryOperator &I);
186 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000187 Instruction *commonDivTransforms(BinaryOperator &I);
188 Instruction *commonIDivTransforms(BinaryOperator &I);
189 Instruction *visitUDiv(BinaryOperator &I);
190 Instruction *visitSDiv(BinaryOperator &I);
191 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000192 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000193 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000194 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000195 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000196 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000197 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000198 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000199 Instruction *visitOr (BinaryOperator &I);
200 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000201 Instruction *visitShl(BinaryOperator &I);
202 Instruction *visitAShr(BinaryOperator &I);
203 Instruction *visitLShr(BinaryOperator &I);
204 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000205 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
206 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000207 Instruction *visitFCmpInst(FCmpInst &I);
208 Instruction *visitICmpInst(ICmpInst &I);
209 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000210 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
211 Instruction *LHS,
212 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000213 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
214 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000215
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000216 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000217 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000218 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000219 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000220 Instruction *commonCastTransforms(CastInst &CI);
221 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000222 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000223 Instruction *visitTrunc(TruncInst &CI);
224 Instruction *visitZExt(ZExtInst &CI);
225 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000226 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000227 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000228 Instruction *visitFPToUI(FPToUIInst &FI);
229 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000230 Instruction *visitUIToFP(CastInst &CI);
231 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000232 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000233 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000234 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000235 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
236 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000237 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000238 Instruction *visitSelectInst(SelectInst &SI);
239 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000240 Instruction *visitCallInst(CallInst &CI);
241 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000242 Instruction *visitPHINode(PHINode &PN);
243 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000244 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000245 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000246 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000247 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000248 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000249 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000250 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000251 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000252 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000253 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000254
255 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000256 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000257
Chris Lattner9fe38862003-06-19 17:00:31 +0000258 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000259 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000260 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000261 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000262 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
263 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000264 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000265 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
266
Chris Lattner9fe38862003-06-19 17:00:31 +0000267
Chris Lattner28977af2004-04-05 01:30:19 +0000268 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000269 // InsertNewInstBefore - insert an instruction New before instruction Old
270 // in the program. Add the new instruction to the worklist.
271 //
Chris Lattner955f3312004-09-28 21:48:02 +0000272 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000273 assert(New && New->getParent() == 0 &&
274 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000275 BasicBlock *BB = Old.getParent();
276 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000277 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000278 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000279 }
280
Chris Lattner0c967662004-09-24 15:21:34 +0000281 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
282 /// This also adds the cast to the worklist. Finally, this returns the
283 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000284 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
285 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000286 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000287
Chris Lattnere2ed0572006-04-06 19:19:17 +0000288 if (Constant *CV = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000289 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000290
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000291 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000292 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000293 return C;
294 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000295
296 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
297 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
298 }
299
Chris Lattner0c967662004-09-24 15:21:34 +0000300
Chris Lattner8b170942002-08-09 23:47:40 +0000301 // ReplaceInstUsesWith - This method is to be used when an instruction is
302 // found to be dead, replacable with another preexisting expression. Here
303 // we add all uses of I to the worklist, replace all uses of I with the new
304 // value, then return I, so that the inst combiner will know that I was
305 // modified.
306 //
307 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000308 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000309 if (&I != V) {
310 I.replaceAllUsesWith(V);
311 return &I;
312 } else {
313 // If we are replacing the instruction with itself, this must be in a
314 // segment of unreachable code, so just clobber the instruction.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000315 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000316 return &I;
317 }
Chris Lattner8b170942002-08-09 23:47:40 +0000318 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000319
320 // EraseInstFromFunction - When dealing with an instruction that has side
321 // effects or produces a void value, we can't rely on DCE to delete the
322 // instruction. Instead, visit methods should return the value returned by
323 // this function.
324 Instruction *EraseInstFromFunction(Instruction &I) {
325 assert(I.use_empty() && "Cannot erase instruction that is used!");
326 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000327 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000328 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000329 return 0; // Don't do anything with FI
330 }
Chris Lattner173234a2008-06-02 01:18:21 +0000331
332 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
333 APInt &KnownOne, unsigned Depth = 0) const {
334 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
335 }
336
337 bool MaskedValueIsZero(Value *V, const APInt &Mask,
338 unsigned Depth = 0) const {
339 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
340 }
341 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
342 return llvm::ComputeNumSignBits(Op, TD, Depth);
343 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000344
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000345 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000346
Reid Spencere4d87aa2006-12-23 06:05:41 +0000347 /// SimplifyCommutative - This performs a few simplifications for
348 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000349 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000350
Reid Spencere4d87aa2006-12-23 06:05:41 +0000351 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
352 /// most-complex to least-complex order.
353 bool SimplifyCompare(CmpInst &I);
354
Chris Lattner886ab6c2009-01-31 08:15:18 +0000355 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
356 /// based on the demanded bits.
357 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
358 APInt& KnownZero, APInt& KnownOne,
359 unsigned Depth);
360 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000361 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000362 unsigned Depth=0);
363
364 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
365 /// SimplifyDemandedBits knows about. See if the instruction has any
366 /// properties that allow us to simplify its operands.
367 bool SimplifyDemandedInstructionBits(Instruction &Inst);
368
Evan Cheng388df622009-02-03 10:05:09 +0000369 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
370 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000371
Chris Lattner4e998b22004-09-29 05:07:12 +0000372 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
373 // PHI node as operand #0, see if we can fold the instruction into the PHI
374 // (which is only possible if all operands to the PHI are constants).
375 Instruction *FoldOpIntoPhi(Instruction &I);
376
Chris Lattnerbac32862004-11-14 19:13:23 +0000377 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
378 // operator and they all are only used by the PHI, PHI together their
379 // inputs, and do the operation once, to the result of the PHI.
380 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000381 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000382 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
383
Chris Lattner7da52b22006-11-01 04:51:18 +0000384
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000385 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
386 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000387
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000388 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000389 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000390 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000391 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000392 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000393 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000394 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000395 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000396 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000397
Chris Lattnerafe91a52006-06-15 19:07:26 +0000398
Reid Spencerc55b2432006-12-13 18:21:21 +0000399 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000400
Dan Gohman6de29f82009-06-15 22:12:54 +0000401 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000402 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000403 unsigned GetOrEnforceKnownAlignment(Value *V,
404 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000405
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000406 };
407}
408
Dan Gohman844731a2008-05-13 00:00:25 +0000409char InstCombiner::ID = 0;
410static RegisterPass<InstCombiner>
411X("instcombine", "Combine redundant instructions");
412
Chris Lattner4f98c562003-03-10 21:43:22 +0000413// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000414// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000415static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000416 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000417 if (BinaryOperator::isNeg(V) ||
418 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000419 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000420 return 3;
421 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000422 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000423 if (isa<Argument>(V)) return 3;
424 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000425}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000426
Chris Lattnerc8802d22003-03-11 00:12:48 +0000427// isOnlyUse - Return true if this instruction will be deleted if we stop using
428// it.
429static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000430 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000431}
432
Chris Lattner4cb170c2004-02-23 06:38:22 +0000433// getPromotedType - Return the specified type promoted as it would be to pass
434// though a va_arg area...
435static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000436 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
437 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000438 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000439 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000440 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000441}
442
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000443/// getBitCastOperand - If the specified operand is a CastInst, a constant
444/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
445/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000446static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000447 if (Operator *O = dyn_cast<Operator>(V)) {
448 if (O->getOpcode() == Instruction::BitCast)
449 return O->getOperand(0);
450 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
451 if (GEP->hasAllZeroIndices())
452 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000453 }
Chris Lattnereed48272005-09-13 00:40:14 +0000454 return 0;
455}
456
Reid Spencer3da59db2006-11-27 01:05:10 +0000457/// This function is a wrapper around CastInst::isEliminableCastPair. It
458/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000459static Instruction::CastOps
460isEliminableCastPair(
461 const CastInst *CI, ///< The first cast instruction
462 unsigned opcode, ///< The opcode of the second cast instruction
463 const Type *DstTy, ///< The target type for the second cast instruction
464 TargetData *TD ///< The target data for pointer size
465) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000466
Reid Spencer3da59db2006-11-27 01:05:10 +0000467 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
468 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000469
Reid Spencer3da59db2006-11-27 01:05:10 +0000470 // Get the opcodes of the two Cast instructions
471 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
472 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000473
Chris Lattnera0e69692009-03-24 18:35:40 +0000474 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000475 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000476 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000477
478 // We don't want to form an inttoptr or ptrtoint that converts to an integer
479 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000480 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000481 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000482 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000483 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000484 Res = 0;
485
486 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000487}
488
489/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
490/// in any code being generated. It does not require codegen if V is simple
491/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000492static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
493 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000494 if (V->getType() == Ty || isa<Constant>(V)) return false;
495
Chris Lattner01575b72006-05-25 23:24:33 +0000496 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000497 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000498 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000499 return false;
500 return true;
501}
502
Chris Lattner4f98c562003-03-10 21:43:22 +0000503// SimplifyCommutative - This performs a few simplifications for commutative
504// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000505//
Chris Lattner4f98c562003-03-10 21:43:22 +0000506// 1. Order operands such that they are listed from right (least complex) to
507// left (most complex). This puts constants before unary operators before
508// binary operators.
509//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000510// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
511// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000512//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000513bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000514 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000515 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000516 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000517
Chris Lattner4f98c562003-03-10 21:43:22 +0000518 if (!I.isAssociative()) return Changed;
519 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000520 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
521 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
522 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000523 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000524 cast<Constant>(I.getOperand(1)),
525 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000526 I.setOperand(0, Op->getOperand(0));
527 I.setOperand(1, Folded);
528 return true;
529 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
530 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
531 isOnlyUse(Op) && isOnlyUse(Op1)) {
532 Constant *C1 = cast<Constant>(Op->getOperand(1));
533 Constant *C2 = cast<Constant>(Op1->getOperand(1));
534
535 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000536 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000537 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000538 Op1->getOperand(0),
539 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000540 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000541 I.setOperand(0, New);
542 I.setOperand(1, Folded);
543 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000544 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000545 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000546 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000547}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000548
Reid Spencere4d87aa2006-12-23 06:05:41 +0000549/// SimplifyCompare - For a CmpInst this function just orders the operands
550/// so that theyare listed from right (least complex) to left (most complex).
551/// This puts constants before unary operators before binary operators.
552bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman14ef4f02009-08-29 23:39:38 +0000553 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000554 return false;
555 I.swapOperands();
556 // Compare instructions are not associative so there's nothing else we can do.
557 return true;
558}
559
Chris Lattner8d969642003-03-10 23:06:50 +0000560// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
561// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000562//
Dan Gohman186a6362009-08-12 16:04:34 +0000563static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000564 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000565 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000566
Chris Lattner0ce85802004-12-14 20:08:06 +0000567 // Constants can be considered to be negated values if they can be folded.
568 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000569 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000570
571 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
572 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000573 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000574
Chris Lattner8d969642003-03-10 23:06:50 +0000575 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000576}
577
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000578// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
579// instruction if the LHS is a constant negative zero (which is the 'negate'
580// form).
581//
Dan Gohman186a6362009-08-12 16:04:34 +0000582static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000583 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000584 return BinaryOperator::getFNegArgument(V);
585
586 // Constants can be considered to be negated values if they can be folded.
587 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000588 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000589
590 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
591 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000592 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000593
594 return 0;
595}
596
Dan Gohman186a6362009-08-12 16:04:34 +0000597static inline Value *dyn_castNotVal(Value *V) {
Chris Lattner8d969642003-03-10 23:06:50 +0000598 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000599 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000600
601 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000602 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000603 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000604 return 0;
605}
606
Chris Lattnerc8802d22003-03-11 00:12:48 +0000607// dyn_castFoldableMul - If this value is a multiply that can be folded into
608// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000609// non-constant operand of the multiply, and set CST to point to the multiplier.
610// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000611//
Dan Gohman186a6362009-08-12 16:04:34 +0000612static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000613 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000614 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000615 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000616 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000617 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000618 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000619 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000620 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000621 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000622 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000623 CST = ConstantInt::get(V->getType()->getContext(),
624 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000625 return I->getOperand(0);
626 }
627 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000628 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000629}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000630
Reid Spencer7177c3a2007-03-25 05:33:51 +0000631/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000632static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000633 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000634 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000635}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000636/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000637static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000638 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000639 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000640}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000641/// MultiplyOverflows - True if the multiply can not be expressed in an int
642/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000643static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000644 uint32_t W = C1->getBitWidth();
645 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
646 if (sign) {
647 LHSExt.sext(W * 2);
648 RHSExt.sext(W * 2);
649 } else {
650 LHSExt.zext(W * 2);
651 RHSExt.zext(W * 2);
652 }
653
654 APInt MulExt = LHSExt * RHSExt;
655
656 if (sign) {
657 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
658 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
659 return MulExt.slt(Min) || MulExt.sgt(Max);
660 } else
661 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
662}
Chris Lattner955f3312004-09-28 21:48:02 +0000663
Reid Spencere7816b52007-03-08 01:52:58 +0000664
Chris Lattner255d8912006-02-11 09:31:47 +0000665/// ShrinkDemandedConstant - Check to see if the specified operand of the
666/// specified instruction is a constant integer. If so, check to see if there
667/// are any bits set in the constant that are not demanded. If so, shrink the
668/// constant and return true.
669static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000670 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000671 assert(I && "No instruction?");
672 assert(OpNo < I->getNumOperands() && "Operand index too large");
673
674 // If the operand is not a constant integer, nothing to do.
675 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
676 if (!OpC) return false;
677
678 // If there are no bits set that aren't demanded, nothing to do.
679 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
680 if ((~Demanded & OpC->getValue()) == 0)
681 return false;
682
683 // This instruction is producing bits that are not demanded. Shrink the RHS.
684 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000685 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000686 return true;
687}
688
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000689// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
690// set of known zero and one bits, compute the maximum and minimum values that
691// could have the specified known zero and known one bits, returning them in
692// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000693static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000694 const APInt& KnownOne,
695 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000696 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
697 KnownZero.getBitWidth() == Min.getBitWidth() &&
698 KnownZero.getBitWidth() == Max.getBitWidth() &&
699 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000700 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000701
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000702 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
703 // bit if it is unknown.
704 Min = KnownOne;
705 Max = KnownOne|UnknownBits;
706
Dan Gohman1c8491e2009-04-25 17:12:48 +0000707 if (UnknownBits.isNegative()) { // Sign bit is unknown
708 Min.set(Min.getBitWidth()-1);
709 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000710 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000711}
712
713// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
714// a set of known zero and one bits, compute the maximum and minimum values that
715// could have the specified known zero and known one bits, returning them in
716// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000717static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000718 const APInt &KnownOne,
719 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000720 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
721 KnownZero.getBitWidth() == Min.getBitWidth() &&
722 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000723 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000724 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000725
726 // The minimum value is when the unknown bits are all zeros.
727 Min = KnownOne;
728 // The maximum value is when the unknown bits are all ones.
729 Max = KnownOne|UnknownBits;
730}
Chris Lattner255d8912006-02-11 09:31:47 +0000731
Chris Lattner886ab6c2009-01-31 08:15:18 +0000732/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
733/// SimplifyDemandedBits knows about. See if the instruction has any
734/// properties that allow us to simplify its operands.
735bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000736 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000737 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
738 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
739
740 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
741 KnownZero, KnownOne, 0);
742 if (V == 0) return false;
743 if (V == &Inst) return true;
744 ReplaceInstUsesWith(Inst, V);
745 return true;
746}
747
748/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
749/// specified instruction operand if possible, updating it in place. It returns
750/// true if it made any change and false otherwise.
751bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
752 APInt &KnownZero, APInt &KnownOne,
753 unsigned Depth) {
754 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
755 KnownZero, KnownOne, Depth);
756 if (NewVal == 0) return false;
757 U.set(NewVal);
758 return true;
759}
760
761
762/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
763/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000764/// that only the bits set in DemandedMask of the result of V are ever used
765/// downstream. Consequently, depending on the mask and V, it may be possible
766/// to replace V with a constant or one of its operands. In such cases, this
767/// function does the replacement and returns true. In all other cases, it
768/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000769/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000770/// to be zero in the expression. These are provided to potentially allow the
771/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
772/// the expression. KnownOne and KnownZero always follow the invariant that
773/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
774/// the bits in KnownOne and KnownZero may only be accurate for those bits set
775/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
776/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000777///
778/// This returns null if it did not change anything and it permits no
779/// simplification. This returns V itself if it did some simplification of V's
780/// operands based on the information about what bits are demanded. This returns
781/// some other non-null value if it found out that V is equal to another value
782/// in the context where the specified bits are demanded, but not for all users.
783Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
784 APInt &KnownZero, APInt &KnownOne,
785 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000786 assert(V != 0 && "Null pointer of Value???");
787 assert(Depth <= 6 && "Limit Search Depth");
788 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000789 const Type *VTy = V->getType();
790 assert((TD || !isa<PointerType>(VTy)) &&
791 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000792 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
793 (!VTy->isIntOrIntVector() ||
794 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000795 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000796 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000797 "Value *V, DemandedMask, KnownZero and KnownOne "
798 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000799 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
800 // We know all of the bits for a constant!
801 KnownOne = CI->getValue() & DemandedMask;
802 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000803 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000804 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000805 if (isa<ConstantPointerNull>(V)) {
806 // We know all of the bits for a constant!
807 KnownOne.clear();
808 KnownZero = DemandedMask;
809 return 0;
810 }
811
Chris Lattner08d2cc72009-01-31 07:26:06 +0000812 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000813 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000814 if (DemandedMask == 0) { // Not demanding any bits from V.
815 if (isa<UndefValue>(V))
816 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000817 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000818 }
819
Chris Lattner4598c942009-01-31 08:24:16 +0000820 if (Depth == 6) // Limit search depth.
821 return 0;
822
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000823 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
824 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
825
Dan Gohman1c8491e2009-04-25 17:12:48 +0000826 Instruction *I = dyn_cast<Instruction>(V);
827 if (!I) {
828 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
829 return 0; // Only analyze instructions.
830 }
831
Chris Lattner4598c942009-01-31 08:24:16 +0000832 // If there are multiple uses of this value and we aren't at the root, then
833 // we can't do any simplifications of the operands, because DemandedMask
834 // only reflects the bits demanded by *one* of the users.
835 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000836 // Despite the fact that we can't simplify this instruction in all User's
837 // context, we can at least compute the knownzero/knownone bits, and we can
838 // do simplifications that apply to *just* the one user if we know that
839 // this instruction has a simpler value in that context.
840 if (I->getOpcode() == Instruction::And) {
841 // If either the LHS or the RHS are Zero, the result is zero.
842 ComputeMaskedBits(I->getOperand(1), DemandedMask,
843 RHSKnownZero, RHSKnownOne, Depth+1);
844 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
845 LHSKnownZero, LHSKnownOne, Depth+1);
846
847 // If all of the demanded bits are known 1 on one side, return the other.
848 // These bits cannot contribute to the result of the 'and' in this
849 // context.
850 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
851 (DemandedMask & ~LHSKnownZero))
852 return I->getOperand(0);
853 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
854 (DemandedMask & ~RHSKnownZero))
855 return I->getOperand(1);
856
857 // If all of the demanded bits in the inputs are known zeros, return zero.
858 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000859 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000860
861 } else if (I->getOpcode() == Instruction::Or) {
862 // We can simplify (X|Y) -> X or Y in the user's context if we know that
863 // only bits from X or Y are demanded.
864
865 // If either the LHS or the RHS are One, the result is One.
866 ComputeMaskedBits(I->getOperand(1), DemandedMask,
867 RHSKnownZero, RHSKnownOne, Depth+1);
868 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
869 LHSKnownZero, LHSKnownOne, Depth+1);
870
871 // If all of the demanded bits are known zero on one side, return the
872 // other. These bits cannot contribute to the result of the 'or' in this
873 // context.
874 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
875 (DemandedMask & ~LHSKnownOne))
876 return I->getOperand(0);
877 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
878 (DemandedMask & ~RHSKnownOne))
879 return I->getOperand(1);
880
881 // If all of the potentially set bits on one side are known to be set on
882 // the other side, just use the 'other' side.
883 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
884 (DemandedMask & (~RHSKnownZero)))
885 return I->getOperand(0);
886 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
887 (DemandedMask & (~LHSKnownZero)))
888 return I->getOperand(1);
889 }
890
Chris Lattner4598c942009-01-31 08:24:16 +0000891 // Compute the KnownZero/KnownOne bits to simplify things downstream.
892 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
893 return 0;
894 }
895
896 // If this is the root being simplified, allow it to have multiple uses,
897 // just set the DemandedMask to all bits so that we can try to simplify the
898 // operands. This allows visitTruncInst (for example) to simplify the
899 // operand of a trunc without duplicating all the logic below.
900 if (Depth == 0 && !V->hasOneUse())
901 DemandedMask = APInt::getAllOnesValue(BitWidth);
902
Reid Spencer8cb68342007-03-12 17:25:59 +0000903 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000904 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000905 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000906 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000907 case Instruction::And:
908 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000909 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
910 RHSKnownZero, RHSKnownOne, Depth+1) ||
911 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000912 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000913 return I;
914 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
915 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000916
917 // If all of the demanded bits are known 1 on one side, return the other.
918 // These bits cannot contribute to the result of the 'and'.
919 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
920 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000921 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000922 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
923 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000924 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000925
926 // If all of the demanded bits in the inputs are known zeros, return zero.
927 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000928 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000929
930 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000931 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000932 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000933
934 // Output known-1 bits are only known if set in both the LHS & RHS.
935 RHSKnownOne &= LHSKnownOne;
936 // Output known-0 are known to be clear if zero in either the LHS | RHS.
937 RHSKnownZero |= LHSKnownZero;
938 break;
939 case Instruction::Or:
940 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000941 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
942 RHSKnownZero, RHSKnownOne, Depth+1) ||
943 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000944 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000945 return I;
946 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
947 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000948
949 // If all of the demanded bits are known zero on one side, return the other.
950 // These bits cannot contribute to the result of the 'or'.
951 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
952 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000953 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000954 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
955 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000956 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000957
958 // If all of the potentially set bits on one side are known to be set on
959 // the other side, just use the 'other' side.
960 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
961 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000962 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000963 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
964 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000965 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000966
967 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000968 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000969 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000970
971 // Output known-0 bits are only known if clear in both the LHS & RHS.
972 RHSKnownZero &= LHSKnownZero;
973 // Output known-1 are known to be set if set in either the LHS | RHS.
974 RHSKnownOne |= LHSKnownOne;
975 break;
976 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000977 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
978 RHSKnownZero, RHSKnownOne, Depth+1) ||
979 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000980 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000981 return I;
982 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
983 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000984
985 // If all of the demanded bits are known zero on one side, return the other.
986 // These bits cannot contribute to the result of the 'xor'.
987 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000988 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000989 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000990 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000991
992 // Output known-0 bits are known if clear or set in both the LHS & RHS.
993 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
994 (RHSKnownOne & LHSKnownOne);
995 // Output known-1 are known to be set if set in only one of the LHS, RHS.
996 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
997 (RHSKnownOne & LHSKnownZero);
998
999 // If all of the demanded bits are known to be zero on one side or the
1000 // other, turn this into an *inclusive* or.
1001 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1002 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1003 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001004 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001005 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001006 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001007 }
1008
1009 // If all of the demanded bits on one side are known, and all of the set
1010 // bits on that side are also known to be set on the other side, turn this
1011 // into an AND, as we know the bits will be cleared.
1012 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1013 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1014 // all known
1015 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001016 Constant *AndC = Constant::getIntegerValue(VTy,
1017 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001018 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001019 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001020 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001021 }
1022 }
1023
1024 // If the RHS is a constant, see if we can simplify it.
1025 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001026 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001027 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001028
1029 RHSKnownZero = KnownZeroOut;
1030 RHSKnownOne = KnownOneOut;
1031 break;
1032 }
1033 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001034 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1035 RHSKnownZero, RHSKnownOne, Depth+1) ||
1036 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001037 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001038 return I;
1039 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1040 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001041
1042 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001043 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1044 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001045 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001046
1047 // Only known if known in both the LHS and RHS.
1048 RHSKnownOne &= LHSKnownOne;
1049 RHSKnownZero &= LHSKnownZero;
1050 break;
1051 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001052 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001053 DemandedMask.zext(truncBf);
1054 RHSKnownZero.zext(truncBf);
1055 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001056 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001057 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001058 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001059 DemandedMask.trunc(BitWidth);
1060 RHSKnownZero.trunc(BitWidth);
1061 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001062 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001063 break;
1064 }
1065 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001066 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001067 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001068
1069 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1070 if (const VectorType *SrcVTy =
1071 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1072 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1073 // Don't touch a bitcast between vectors of different element counts.
1074 return false;
1075 } else
1076 // Don't touch a scalar-to-vector bitcast.
1077 return false;
1078 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1079 // Don't touch a vector-to-scalar bitcast.
1080 return false;
1081
Chris Lattner886ab6c2009-01-31 08:15:18 +00001082 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001083 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001084 return I;
1085 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001086 break;
1087 case Instruction::ZExt: {
1088 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001089 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001090
Zhou Shengd48653a2007-03-29 04:45:55 +00001091 DemandedMask.trunc(SrcBitWidth);
1092 RHSKnownZero.trunc(SrcBitWidth);
1093 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001094 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001095 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001096 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001097 DemandedMask.zext(BitWidth);
1098 RHSKnownZero.zext(BitWidth);
1099 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001100 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001101 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001102 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001103 break;
1104 }
1105 case Instruction::SExt: {
1106 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001107 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001108
Reid Spencer8cb68342007-03-12 17:25:59 +00001109 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001110 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001111
Zhou Sheng01542f32007-03-29 02:26:30 +00001112 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001113 // If any of the sign extended bits are demanded, we know that the sign
1114 // bit is demanded.
1115 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001116 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001117
Zhou Shengd48653a2007-03-29 04:45:55 +00001118 InputDemandedBits.trunc(SrcBitWidth);
1119 RHSKnownZero.trunc(SrcBitWidth);
1120 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001121 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001122 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001123 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001124 InputDemandedBits.zext(BitWidth);
1125 RHSKnownZero.zext(BitWidth);
1126 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001127 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001128
1129 // If the sign bit of the input is known set or clear, then we know the
1130 // top bits of the result.
1131
1132 // If the input sign bit is known zero, or if the NewBits are not demanded
1133 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001134 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001135 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001136 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1137 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001138 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001139 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001140 }
1141 break;
1142 }
1143 case Instruction::Add: {
1144 // Figure out what the input bits are. If the top bits of the and result
1145 // are not demanded, then the add doesn't demand them from its input
1146 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001147 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001148
1149 // If there is a constant on the RHS, there are a variety of xformations
1150 // we can do.
1151 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1152 // If null, this should be simplified elsewhere. Some of the xforms here
1153 // won't work if the RHS is zero.
1154 if (RHS->isZero())
1155 break;
1156
1157 // If the top bit of the output is demanded, demand everything from the
1158 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001159 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001160
1161 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001162 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001163 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001164 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001165
1166 // If the RHS of the add has bits set that can't affect the input, reduce
1167 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001168 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001169 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001170
1171 // Avoid excess work.
1172 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1173 break;
1174
1175 // Turn it into OR if input bits are zero.
1176 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1177 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001178 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001179 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001180 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001181 }
1182
1183 // We can say something about the output known-zero and known-one bits,
1184 // depending on potential carries from the input constant and the
1185 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1186 // bits set and the RHS constant is 0x01001, then we know we have a known
1187 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1188
1189 // To compute this, we first compute the potential carry bits. These are
1190 // the bits which may be modified. I'm not aware of a better way to do
1191 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001192 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001193 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001194
1195 // Now that we know which bits have carries, compute the known-1/0 sets.
1196
1197 // Bits are known one if they are known zero in one operand and one in the
1198 // other, and there is no input carry.
1199 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1200 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1201
1202 // Bits are known zero if they are known zero in both operands and there
1203 // is no input carry.
1204 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1205 } else {
1206 // If the high-bits of this ADD are not demanded, then it does not demand
1207 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001208 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001209 // Right fill the mask of bits for this ADD to demand the most
1210 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001211 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001212 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1213 LHSKnownZero, LHSKnownOne, Depth+1) ||
1214 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001215 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001216 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001217 }
1218 }
1219 break;
1220 }
1221 case Instruction::Sub:
1222 // If the high-bits of this SUB are not demanded, then it does not demand
1223 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001224 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001225 // Right fill the mask of bits for this SUB to demand the most
1226 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001227 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001228 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001229 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1230 LHSKnownZero, LHSKnownOne, Depth+1) ||
1231 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001232 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001233 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001234 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001235 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1236 // the known zeros and ones.
1237 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001238 break;
1239 case Instruction::Shl:
1240 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001241 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001242 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001243 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001244 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001245 return I;
1246 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001247 RHSKnownZero <<= ShiftAmt;
1248 RHSKnownOne <<= ShiftAmt;
1249 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001250 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001251 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001252 }
1253 break;
1254 case Instruction::LShr:
1255 // For a logical shift right
1256 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001257 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001258
Reid Spencer8cb68342007-03-12 17:25:59 +00001259 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001260 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001261 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001262 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001263 return I;
1264 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001265 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1266 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001267 if (ShiftAmt) {
1268 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001269 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001270 RHSKnownZero |= HighBits; // high bits known zero.
1271 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001272 }
1273 break;
1274 case Instruction::AShr:
1275 // If this is an arithmetic shift right and only the low-bit is set, we can
1276 // always convert this into a logical shr, even if the shift amount is
1277 // variable. The low bit of the shift cannot be an input sign bit unless
1278 // the shift amount is >= the size of the datatype, which is undefined.
1279 if (DemandedMask == 1) {
1280 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001281 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001282 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001283 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001284 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001285
1286 // If the sign bit is the only bit demanded by this ashr, then there is no
1287 // need to do it, the shift doesn't change the high bit.
1288 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001289 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001290
1291 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001292 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001293
Reid Spencer8cb68342007-03-12 17:25:59 +00001294 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001295 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001296 // If any of the "high bits" are demanded, we should set the sign bit as
1297 // demanded.
1298 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1299 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001300 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001301 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001302 return I;
1303 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001304 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001305 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001306 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1307 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1308
1309 // Handle the sign bits.
1310 APInt SignBit(APInt::getSignBit(BitWidth));
1311 // Adjust to where it is now in the mask.
1312 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1313
1314 // If the input sign bit is known to be zero, or if none of the top bits
1315 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001316 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001317 (HighBits & ~DemandedMask) == HighBits) {
1318 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001319 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001320 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001321 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001322 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1323 RHSKnownOne |= HighBits;
1324 }
1325 }
1326 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001327 case Instruction::SRem:
1328 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001329 APInt RA = Rem->getValue().abs();
1330 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001331 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001332 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001333
Nick Lewycky8e394322008-11-02 02:41:50 +00001334 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001335 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001336 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001337 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001338 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001339
1340 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1341 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001342
1343 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001344
Chris Lattner886ab6c2009-01-31 08:15:18 +00001345 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001346 }
1347 }
1348 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001349 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001350 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1351 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001352 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1353 KnownZero2, KnownOne2, Depth+1) ||
1354 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001355 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001356 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001357
Chris Lattner455e9ab2009-01-21 18:09:24 +00001358 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001359 Leaders = std::max(Leaders,
1360 KnownZero2.countLeadingOnes());
1361 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001362 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001363 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001364 case Instruction::Call:
1365 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1366 switch (II->getIntrinsicID()) {
1367 default: break;
1368 case Intrinsic::bswap: {
1369 // If the only bits demanded come from one byte of the bswap result,
1370 // just shift the input byte into position to eliminate the bswap.
1371 unsigned NLZ = DemandedMask.countLeadingZeros();
1372 unsigned NTZ = DemandedMask.countTrailingZeros();
1373
1374 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1375 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1376 // have 14 leading zeros, round to 8.
1377 NLZ &= ~7;
1378 NTZ &= ~7;
1379 // If we need exactly one byte, we can do this transformation.
1380 if (BitWidth-NLZ-NTZ == 8) {
1381 unsigned ResultBit = NTZ;
1382 unsigned InputBit = BitWidth-NTZ-8;
1383
1384 // Replace this with either a left or right shift to get the byte into
1385 // the right place.
1386 Instruction *NewVal;
1387 if (InputBit > ResultBit)
1388 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001389 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001390 else
1391 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001392 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001393 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001394 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001395 }
1396
1397 // TODO: Could compute known zero/one bits based on the input.
1398 break;
1399 }
1400 }
1401 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001402 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001403 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001404 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001405
1406 // If the client is only demanding bits that we know, return the known
1407 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001408 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1409 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001410 return false;
1411}
1412
Chris Lattner867b99f2006-10-05 06:55:50 +00001413
Mon P Wangaeb06d22008-11-10 04:46:22 +00001414/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001415/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001416/// actually used by the caller. This method analyzes which elements of the
1417/// operand are undef and returns that information in UndefElts.
1418///
1419/// If the information about demanded elements can be used to simplify the
1420/// operation, the operation is simplified, then the resultant value is
1421/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001422Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1423 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001424 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001425 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001426 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001427 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001428
1429 if (isa<UndefValue>(V)) {
1430 // If the entire vector is undefined, just return this info.
1431 UndefElts = EltMask;
1432 return 0;
1433 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1434 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001435 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001436 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001437
Chris Lattner867b99f2006-10-05 06:55:50 +00001438 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001439 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1440 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001441 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001442
1443 std::vector<Constant*> Elts;
1444 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001445 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001446 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001447 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001448 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1449 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001450 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001451 } else { // Otherwise, defined.
1452 Elts.push_back(CP->getOperand(i));
1453 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001454
Chris Lattner867b99f2006-10-05 06:55:50 +00001455 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001456 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001457 return NewCP != CP ? NewCP : 0;
1458 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001459 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001460 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001461
1462 // Check if this is identity. If so, return 0 since we are not simplifying
1463 // anything.
1464 if (DemandedElts == ((1ULL << VWidth) -1))
1465 return 0;
1466
Reid Spencer9d6565a2007-02-15 02:26:10 +00001467 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001468 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001469 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001470 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001471 for (unsigned i = 0; i != VWidth; ++i) {
1472 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1473 Elts.push_back(Elt);
1474 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001475 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001476 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001477 }
1478
Dan Gohman488fbfc2008-09-09 18:11:14 +00001479 // Limit search depth.
1480 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001481 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001482
1483 // If multiple users are using the root value, procede with
1484 // simplification conservatively assuming that all elements
1485 // are needed.
1486 if (!V->hasOneUse()) {
1487 // Quit if we find multiple users of a non-root value though.
1488 // They'll be handled when it's their turn to be visited by
1489 // the main instcombine process.
1490 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001491 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001492 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001493
1494 // Conservatively assume that all elements are needed.
1495 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001496 }
1497
1498 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001499 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001500
1501 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001502 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001503 Value *TmpV;
1504 switch (I->getOpcode()) {
1505 default: break;
1506
1507 case Instruction::InsertElement: {
1508 // If this is a variable index, we don't know which element it overwrites.
1509 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001510 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001511 if (Idx == 0) {
1512 // Note that we can't propagate undef elt info, because we don't know
1513 // which elt is getting updated.
1514 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1515 UndefElts2, Depth+1);
1516 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1517 break;
1518 }
1519
1520 // If this is inserting an element that isn't demanded, remove this
1521 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001522 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001523 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001524 return AddSoonDeadInstToWorklist(*I, 0);
1525
1526 // Otherwise, the element inserted overwrites whatever was there, so the
1527 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001528 APInt DemandedElts2 = DemandedElts;
1529 DemandedElts2.clear(IdxNo);
1530 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001531 UndefElts, Depth+1);
1532 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1533
1534 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001535 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001536 break;
1537 }
1538 case Instruction::ShuffleVector: {
1539 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001540 uint64_t LHSVWidth =
1541 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001542 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001543 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001544 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001545 unsigned MaskVal = Shuffle->getMaskValue(i);
1546 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001547 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001548 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001549 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001550 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001551 else
Evan Cheng388df622009-02-03 10:05:09 +00001552 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001553 }
1554 }
1555 }
1556
Nate Begeman7b254672009-02-11 22:36:25 +00001557 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001558 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001559 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001560 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1561
Nate Begeman7b254672009-02-11 22:36:25 +00001562 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001563 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1564 UndefElts3, Depth+1);
1565 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1566
1567 bool NewUndefElts = false;
1568 for (unsigned i = 0; i < VWidth; i++) {
1569 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001570 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001571 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001572 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001573 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001574 NewUndefElts = true;
1575 UndefElts.set(i);
1576 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001577 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001578 if (UndefElts3[MaskVal - LHSVWidth]) {
1579 NewUndefElts = true;
1580 UndefElts.set(i);
1581 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001582 }
1583 }
1584
1585 if (NewUndefElts) {
1586 // Add additional discovered undefs.
1587 std::vector<Constant*> Elts;
1588 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001589 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001590 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001591 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001592 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001593 Shuffle->getMaskValue(i)));
1594 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001595 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001596 MadeChange = true;
1597 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001598 break;
1599 }
Chris Lattner69878332007-04-14 22:29:23 +00001600 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001601 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001602 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1603 if (!VTy) break;
1604 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001605 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001606 unsigned Ratio;
1607
1608 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001609 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001610 // elements as are demanded of us.
1611 Ratio = 1;
1612 InputDemandedElts = DemandedElts;
1613 } else if (VWidth > InVWidth) {
1614 // Untested so far.
1615 break;
1616
1617 // If there are more elements in the result than there are in the source,
1618 // then an input element is live if any of the corresponding output
1619 // elements are live.
1620 Ratio = VWidth/InVWidth;
1621 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001622 if (DemandedElts[OutIdx])
1623 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001624 }
1625 } else {
1626 // Untested so far.
1627 break;
1628
1629 // If there are more elements in the source than there are in the result,
1630 // then an input element is live if the corresponding output element is
1631 // live.
1632 Ratio = InVWidth/VWidth;
1633 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001634 if (DemandedElts[InIdx/Ratio])
1635 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001636 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001637
Chris Lattner69878332007-04-14 22:29:23 +00001638 // div/rem demand all inputs, because they don't want divide by zero.
1639 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1640 UndefElts2, Depth+1);
1641 if (TmpV) {
1642 I->setOperand(0, TmpV);
1643 MadeChange = true;
1644 }
1645
1646 UndefElts = UndefElts2;
1647 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001648 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001649 // If there are more elements in the result than there are in the source,
1650 // then an output element is undef if the corresponding input element is
1651 // undef.
1652 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001653 if (UndefElts2[OutIdx/Ratio])
1654 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001655 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001656 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001657 // If there are more elements in the source than there are in the result,
1658 // then a result element is undef if all of the corresponding input
1659 // elements are undef.
1660 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1661 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001662 if (!UndefElts2[InIdx]) // Not undef?
1663 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001664 }
1665 break;
1666 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001667 case Instruction::And:
1668 case Instruction::Or:
1669 case Instruction::Xor:
1670 case Instruction::Add:
1671 case Instruction::Sub:
1672 case Instruction::Mul:
1673 // div/rem demand all inputs, because they don't want divide by zero.
1674 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1675 UndefElts, Depth+1);
1676 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1677 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1678 UndefElts2, Depth+1);
1679 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1680
1681 // Output elements are undefined if both are undefined. Consider things
1682 // like undef&0. The result is known zero, not undef.
1683 UndefElts &= UndefElts2;
1684 break;
1685
1686 case Instruction::Call: {
1687 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1688 if (!II) break;
1689 switch (II->getIntrinsicID()) {
1690 default: break;
1691
1692 // Binary vector operations that work column-wise. A dest element is a
1693 // function of the corresponding input elements from the two inputs.
1694 case Intrinsic::x86_sse_sub_ss:
1695 case Intrinsic::x86_sse_mul_ss:
1696 case Intrinsic::x86_sse_min_ss:
1697 case Intrinsic::x86_sse_max_ss:
1698 case Intrinsic::x86_sse2_sub_sd:
1699 case Intrinsic::x86_sse2_mul_sd:
1700 case Intrinsic::x86_sse2_min_sd:
1701 case Intrinsic::x86_sse2_max_sd:
1702 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1703 UndefElts, Depth+1);
1704 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1705 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1706 UndefElts2, Depth+1);
1707 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1708
1709 // If only the low elt is demanded and this is a scalarizable intrinsic,
1710 // scalarize it now.
1711 if (DemandedElts == 1) {
1712 switch (II->getIntrinsicID()) {
1713 default: break;
1714 case Intrinsic::x86_sse_sub_ss:
1715 case Intrinsic::x86_sse_mul_ss:
1716 case Intrinsic::x86_sse2_sub_sd:
1717 case Intrinsic::x86_sse2_mul_sd:
1718 // TODO: Lower MIN/MAX/ABS/etc
1719 Value *LHS = II->getOperand(1);
1720 Value *RHS = II->getOperand(2);
1721 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001722 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001723 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001724 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001725 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001726
1727 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001728 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001729 case Intrinsic::x86_sse_sub_ss:
1730 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001731 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001732 II->getName()), *II);
1733 break;
1734 case Intrinsic::x86_sse_mul_ss:
1735 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001736 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001737 II->getName()), *II);
1738 break;
1739 }
1740
1741 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001742 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001743 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001744 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001745 InsertNewInstBefore(New, *II);
1746 AddSoonDeadInstToWorklist(*II, 0);
1747 return New;
1748 }
1749 }
1750
1751 // Output elements are undefined if both are undefined. Consider things
1752 // like undef&0. The result is known zero, not undef.
1753 UndefElts &= UndefElts2;
1754 break;
1755 }
1756 break;
1757 }
1758 }
1759 return MadeChange ? I : 0;
1760}
1761
Dan Gohman45b4e482008-05-19 22:14:15 +00001762
Chris Lattner564a7272003-08-13 19:01:45 +00001763/// AssociativeOpt - Perform an optimization on an associative operator. This
1764/// function is designed to check a chain of associative operators for a
1765/// potential to apply a certain optimization. Since the optimization may be
1766/// applicable if the expression was reassociated, this checks the chain, then
1767/// reassociates the expression as necessary to expose the optimization
1768/// opportunity. This makes use of a special Functor, which must define
1769/// 'shouldApply' and 'apply' methods.
1770///
1771template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001772static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001773 unsigned Opcode = Root.getOpcode();
1774 Value *LHS = Root.getOperand(0);
1775
1776 // Quick check, see if the immediate LHS matches...
1777 if (F.shouldApply(LHS))
1778 return F.apply(Root);
1779
1780 // Otherwise, if the LHS is not of the same opcode as the root, return.
1781 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001782 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001783 // Should we apply this transform to the RHS?
1784 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1785
1786 // If not to the RHS, check to see if we should apply to the LHS...
1787 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1788 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1789 ShouldApply = true;
1790 }
1791
1792 // If the functor wants to apply the optimization to the RHS of LHSI,
1793 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1794 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001795 // Now all of the instructions are in the current basic block, go ahead
1796 // and perform the reassociation.
1797 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1798
1799 // First move the selected RHS to the LHS of the root...
1800 Root.setOperand(0, LHSI->getOperand(1));
1801
1802 // Make what used to be the LHS of the root be the user of the root...
1803 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001804 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001805 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001806 return 0;
1807 }
Chris Lattner65725312004-04-16 18:08:07 +00001808 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001809 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001810 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001811 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001812 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001813
1814 // Now propagate the ExtraOperand down the chain of instructions until we
1815 // get to LHSI.
1816 while (TmpLHSI != LHSI) {
1817 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001818 // Move the instruction to immediately before the chain we are
1819 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001820 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001821 ARI = NextLHSI;
1822
Chris Lattner564a7272003-08-13 19:01:45 +00001823 Value *NextOp = NextLHSI->getOperand(1);
1824 NextLHSI->setOperand(1, ExtraOperand);
1825 TmpLHSI = NextLHSI;
1826 ExtraOperand = NextOp;
1827 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001828
Chris Lattner564a7272003-08-13 19:01:45 +00001829 // Now that the instructions are reassociated, have the functor perform
1830 // the transformation...
1831 return F.apply(Root);
1832 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001833
Chris Lattner564a7272003-08-13 19:01:45 +00001834 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1835 }
1836 return 0;
1837}
1838
Dan Gohman844731a2008-05-13 00:00:25 +00001839namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001840
Nick Lewycky02d639f2008-05-23 04:34:58 +00001841// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001842struct AddRHS {
1843 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001844 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001845 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1846 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001847 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001848 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001849 }
1850};
1851
1852// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1853// iff C1&C2 == 0
1854struct AddMaskingAnd {
1855 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001856 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001857 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001858 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001859 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001860 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001861 }
1862 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001863 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001864 }
1865};
1866
Dan Gohman844731a2008-05-13 00:00:25 +00001867}
1868
Chris Lattner6e7ba452005-01-01 16:22:27 +00001869static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001870 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001871 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001872 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001873 }
1874
Chris Lattner2eefe512004-04-09 19:05:30 +00001875 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001876 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1877 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001878
Chris Lattner2eefe512004-04-09 19:05:30 +00001879 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1880 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001881 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1882 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001883 }
1884
1885 Value *Op0 = SO, *Op1 = ConstOperand;
1886 if (!ConstIsRHS)
1887 std::swap(Op0, Op1);
1888 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001889 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001890 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001891 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001892 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +00001893 Op0, Op1, SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001894 else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001895 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001896 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001897 return IC->InsertNewInstBefore(New, I);
1898}
1899
1900// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1901// constant as the other operand, try to fold the binary operator into the
1902// select arguments. This also works for Cast instructions, which obviously do
1903// not have a second operand.
1904static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1905 InstCombiner *IC) {
1906 // Don't modify shared select instructions
1907 if (!SI->hasOneUse()) return 0;
1908 Value *TV = SI->getOperand(1);
1909 Value *FV = SI->getOperand(2);
1910
1911 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001912 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00001913 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001914
Chris Lattner6e7ba452005-01-01 16:22:27 +00001915 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1916 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1917
Gabor Greif051a9502008-04-06 20:25:17 +00001918 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1919 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001920 }
1921 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001922}
1923
Chris Lattner4e998b22004-09-29 05:07:12 +00001924
1925/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1926/// node as operand #0, see if we can fold the instruction into the PHI (which
1927/// is only possible if all operands to the PHI are constants).
1928Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1929 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001930 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001931 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001932
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001933 // Check to see if all of the operands of the PHI are constants. If there is
1934 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001935 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001936 BasicBlock *NonConstBB = 0;
1937 for (unsigned i = 0; i != NumPHIValues; ++i)
1938 if (!isa<Constant>(PN->getIncomingValue(i))) {
1939 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001940 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001941 NonConstBB = PN->getIncomingBlock(i);
1942
1943 // If the incoming non-constant value is in I's block, we have an infinite
1944 // loop.
1945 if (NonConstBB == I.getParent())
1946 return 0;
1947 }
1948
1949 // If there is exactly one non-constant value, we can insert a copy of the
1950 // operation in that block. However, if this is a critical edge, we would be
1951 // inserting the computation one some other paths (e.g. inside a loop). Only
1952 // do this if the pred block is unconditionally branching into the phi block.
1953 if (NonConstBB) {
1954 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1955 if (!BI || !BI->isUnconditional()) return 0;
1956 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001957
1958 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001959 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001960 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001961 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001962 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001963
1964 // Next, add all of the operands to the PHI.
1965 if (I.getNumOperands() == 2) {
1966 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001967 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001968 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001969 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001970 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001971 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001972 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001973 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001974 } else {
1975 assert(PN->getIncomingBlock(i) == NonConstBB);
1976 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001977 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001978 PN->getIncomingValue(i), C, "phitmp",
1979 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001980 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001981 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001982 CI->getPredicate(),
1983 PN->getIncomingValue(i), C, "phitmp",
1984 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001985 else
Torok Edwinc23197a2009-07-14 16:55:14 +00001986 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001987
Chris Lattnerdbab3862007-03-02 21:28:56 +00001988 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001989 }
1990 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001991 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001992 } else {
1993 CastInst *CI = cast<CastInst>(&I);
1994 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001995 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001996 Value *InV;
1997 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001998 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001999 } else {
2000 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002001 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002002 I.getType(), "phitmp",
2003 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002004 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002005 }
2006 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002007 }
2008 }
2009 return ReplaceInstUsesWith(I, NewPN);
2010}
2011
Chris Lattner2454a2e2008-01-29 06:52:45 +00002012
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002013/// WillNotOverflowSignedAdd - Return true if we can prove that:
2014/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2015/// This basically requires proving that the add in the original type would not
2016/// overflow to change the sign bit or have a carry out.
2017bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2018 // There are different heuristics we can use for this. Here are some simple
2019 // ones.
2020
2021 // Add has the property that adding any two 2's complement numbers can only
2022 // have one carry bit which can change a sign. As such, if LHS and RHS each
2023 // have at least two sign bits, we know that the addition of the two values will
2024 // sign extend fine.
2025 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2026 return true;
2027
2028
2029 // If one of the operands only has one non-zero bit, and if the other operand
2030 // has a known-zero bit in a more significant place than it (not including the
2031 // sign bit) the ripple may go up to and fill the zero, but won't change the
2032 // sign. For example, (X & ~4) + 1.
2033
2034 // TODO: Implement.
2035
2036 return false;
2037}
2038
Chris Lattner2454a2e2008-01-29 06:52:45 +00002039
Chris Lattner7e708292002-06-25 16:13:24 +00002040Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002041 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002042 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002043
Chris Lattner66331a42004-04-10 22:01:55 +00002044 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002045 // X + undef -> undef
2046 if (isa<UndefValue>(RHS))
2047 return ReplaceInstUsesWith(I, RHS);
2048
Chris Lattner66331a42004-04-10 22:01:55 +00002049 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002050 if (RHSC->isNullValue())
2051 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002052
Chris Lattner66331a42004-04-10 22:01:55 +00002053 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002054 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002055 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002056 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002057 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002058 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002059
2060 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2061 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002062 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002063 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002064
Eli Friedman709b33d2009-07-13 22:27:52 +00002065 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002066 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002067 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002068 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002069 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002070
2071 if (isa<PHINode>(LHS))
2072 if (Instruction *NV = FoldOpIntoPhi(I))
2073 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002074
Chris Lattner4f637d42006-01-06 17:59:59 +00002075 ConstantInt *XorRHS = 0;
2076 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002077 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002078 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002079 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002080 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002081
Zhou Sheng4351c642007-04-02 08:20:41 +00002082 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002083 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2084 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002085 do {
2086 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002087 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2088 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002089 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2090 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002091 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002092 if (!MaskedValueIsZero(XorLHS,
2093 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002094 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002095 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002096 }
2097 }
2098 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002099 C0080Val = APIntOps::lshr(C0080Val, Size);
2100 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2101 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002102
Reid Spencer35c38852007-03-28 01:36:16 +00002103 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002104 // with funny bit widths then this switch statement should be removed. It
2105 // is just here to get the size of the "middle" type back up to something
2106 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002107 const Type *MiddleType = 0;
2108 switch (Size) {
2109 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002110 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2111 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2112 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002113 }
2114 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002115 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002116 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002117 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002118 }
2119 }
Chris Lattner66331a42004-04-10 22:01:55 +00002120 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002121
Owen Anderson1d0be152009-08-13 21:58:54 +00002122 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002123 return BinaryOperator::CreateXor(LHS, RHS);
2124
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002125 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002126 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002127 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002128 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)
Dan Gohman186a6362009-08-12 16:04:34 +00002144 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002145 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002146 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);
Dan Gohman4ae51262009-08-12 16:23:25 +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))
Dan Gohman186a6362009-08-12 16:04:34 +00002158 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;
Dan Gohman186a6362009-08-12 16:04:34 +00002163 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002164 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +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;
Dan Gohman186a6362009-08-12 16:04:34 +00002169 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002170 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002171 }
2172
2173 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002174 if (dyn_castFoldableMul(RHS, C2) == LHS)
2175 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
Dan Gohman186a6362009-08-12 16:04:34 +00002178 if (dyn_castNotVal(LHS) == RHS ||
2179 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002180 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002181
Chris Lattnerad3448c2003-02-18 19:57:07 +00002182
Chris Lattner564a7272003-08-13 19:01:45 +00002183 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002184 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2185 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002186 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002187
2188 // A+B --> A|B iff A and B have no bits set in common.
2189 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2190 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2191 APInt LHSKnownOne(IT->getBitWidth(), 0);
2192 APInt LHSKnownZero(IT->getBitWidth(), 0);
2193 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2194 if (LHSKnownZero != 0) {
2195 APInt RHSKnownOne(IT->getBitWidth(), 0);
2196 APInt RHSKnownZero(IT->getBitWidth(), 0);
2197 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2198
2199 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002200 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002201 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002202 }
2203 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002204
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002205 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002206 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002207 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002208 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2209 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002210 if (W != Y) {
2211 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002212 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002213 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002214 std::swap(W, X);
2215 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002216 std::swap(Y, Z);
2217 std::swap(W, X);
2218 }
2219 }
2220
2221 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002222 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002223 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002224 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002225 }
2226 }
2227 }
2228
Chris Lattner6b032052003-10-02 15:11:26 +00002229 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002230 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002231 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002232 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002233
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002234 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002235 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002236 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002237 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002238 if (Anded == CRHS) {
2239 // See if all bits from the first bit set in the Add RHS up are included
2240 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002241 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002242
2243 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002244 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002245
2246 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002247 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002248
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002249 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2250 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002251 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002252 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002253 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002254 }
2255 }
2256 }
2257
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002258 // Try to fold constant add into select arguments.
2259 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002260 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002261 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002262 }
2263
Chris Lattner42790482007-12-20 01:56:58 +00002264 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002265 {
2266 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002267 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002268 if (!SI) {
2269 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002270 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002271 }
Chris Lattner42790482007-12-20 01:56:58 +00002272 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002273 Value *TV = SI->getTrueValue();
2274 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002275 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002276
2277 // Can we fold the add into the argument of the select?
2278 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002279 if (match(FV, m_Zero()) &&
2280 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002281 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002282 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002283 if (match(TV, m_Zero()) &&
2284 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002285 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002286 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002287 }
2288 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002289
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002290 // Check for (add (sext x), y), see if we can merge this into an
2291 // integer add followed by a sext.
2292 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2293 // (add (sext x), cst) --> (sext (add x, cst'))
2294 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2295 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002296 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002297 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002298 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002299 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2300 // Insert the new, smaller add.
2301 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2302 CI, "addconv");
2303 InsertNewInstBefore(NewAdd, I);
2304 return new SExtInst(NewAdd, I.getType());
2305 }
2306 }
2307
2308 // (add (sext x), (sext y)) --> (sext (add int x, y))
2309 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2310 // Only do this if x/y have the same type, if at last one of them has a
2311 // single use (so we don't increase the number of sexts), and if the
2312 // integer add will not overflow.
2313 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2314 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2315 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2316 RHSConv->getOperand(0))) {
2317 // Insert the new integer add.
2318 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2319 RHSConv->getOperand(0),
2320 "addconv");
2321 InsertNewInstBefore(NewAdd, I);
2322 return new SExtInst(NewAdd, I.getType());
2323 }
2324 }
2325 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002326
2327 return Changed ? &I : 0;
2328}
2329
2330Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2331 bool Changed = SimplifyCommutative(I);
2332 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2333
2334 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2335 // X + 0 --> X
2336 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002337 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002338 (I.getType())->getValueAPF()))
2339 return ReplaceInstUsesWith(I, LHS);
2340 }
2341
2342 if (isa<PHINode>(LHS))
2343 if (Instruction *NV = FoldOpIntoPhi(I))
2344 return NV;
2345 }
2346
2347 // -A + B --> B - A
2348 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002349 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002350 return BinaryOperator::CreateFSub(RHS, LHSV);
2351
2352 // A + -B --> A - B
2353 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002354 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002355 return BinaryOperator::CreateFSub(LHS, V);
2356
2357 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2358 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2359 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2360 return ReplaceInstUsesWith(I, LHS);
2361
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002362 // Check for (add double (sitofp x), y), see if we can merge this into an
2363 // integer add followed by a promotion.
2364 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2365 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2366 // ... if the constant fits in the integer value. This is useful for things
2367 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2368 // requires a constant pool load, and generally allows the add to be better
2369 // instcombined.
2370 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2371 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002372 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002373 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002374 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002375 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2376 // Insert the new integer add.
2377 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2378 CI, "addconv");
2379 InsertNewInstBefore(NewAdd, I);
2380 return new SIToFPInst(NewAdd, I.getType());
2381 }
2382 }
2383
2384 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2385 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2386 // Only do this if x/y have the same type, if at last one of them has a
2387 // single use (so we don't increase the number of int->fp conversions),
2388 // and if the integer add will not overflow.
2389 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2390 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2391 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2392 RHSConv->getOperand(0))) {
2393 // Insert the new integer add.
2394 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2395 RHSConv->getOperand(0),
2396 "addconv");
2397 InsertNewInstBefore(NewAdd, I);
2398 return new SIToFPInst(NewAdd, I.getType());
2399 }
2400 }
2401 }
2402
Chris Lattner7e708292002-06-25 16:13:24 +00002403 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002404}
2405
Chris Lattner7e708292002-06-25 16:13:24 +00002406Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002407 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002408
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002409 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002410 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002411
Chris Lattner233f7dc2002-08-12 21:17:25 +00002412 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002413 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002414 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002415
Chris Lattnere87597f2004-10-16 18:11:37 +00002416 if (isa<UndefValue>(Op0))
2417 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2418 if (isa<UndefValue>(Op1))
2419 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2420
Chris Lattnerd65460f2003-11-05 01:06:05 +00002421 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2422 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002423 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002424 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002425
Chris Lattnerd65460f2003-11-05 01:06:05 +00002426 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002427 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002428 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002429 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002430
Chris Lattner76b7a062007-01-15 07:02:54 +00002431 // -(X >>u 31) -> (X >>s 31)
2432 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002433 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002434 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002435 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002436 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002437 // 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 Spencerb83eb642006-10-20 07:07:24 +00002439 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002440 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002441 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002442 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002443 }
2444 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002445 }
2446 else if (SI->getOpcode() == Instruction::AShr) {
2447 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2448 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002449 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002450 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002451 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002452 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002453 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002454 }
2455 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002456 }
2457 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002458 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002459
2460 // Try to fold constant sub into select arguments.
2461 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002462 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002463 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002464
2465 // C - zext(bool) -> bool ? C - 1 : C
2466 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002467 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002468 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002469 }
2470
Owen Anderson1d0be152009-08-13 21:58:54 +00002471 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002472 return BinaryOperator::CreateXor(Op0, Op1);
2473
Chris Lattner43d84d62005-04-07 16:15:25 +00002474 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002475 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002476 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002477 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002478 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002479 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002480 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002481 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002482 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2483 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2484 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002485 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002486 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002487 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002488 }
2489
Chris Lattnerfd059242003-10-15 16:48:29 +00002490 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002491 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2492 // is not used by anyone else...
2493 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002494 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002495 // Swap the two operands of the subexpr...
2496 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2497 Op1I->setOperand(0, IIOp1);
2498 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002499
Chris Lattnera2881962003-02-18 19:28:33 +00002500 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002501 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002502 }
2503
2504 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2505 //
2506 if (Op1I->getOpcode() == Instruction::And &&
2507 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2508 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2509
Chris Lattnerf523d062004-06-09 05:08:07 +00002510 Value *NewNot =
Dan Gohman4ae51262009-08-12 16:23:25 +00002511 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002512 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002513 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002514
Reid Spencerac5209e2006-10-16 23:08:08 +00002515 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002516 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002517 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002518 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002519 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002520 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002521 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002522
Chris Lattnerad3448c2003-02-18 19:57:07 +00002523 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002524 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002525 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002526 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002527 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002528 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002529 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002530 }
Chris Lattner40371712002-05-09 01:29:19 +00002531 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002532 }
Chris Lattnera2881962003-02-18 19:28:33 +00002533
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002534 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2535 if (Op0I->getOpcode() == Instruction::Add) {
2536 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2537 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2538 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2539 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2540 } else if (Op0I->getOpcode() == Instruction::Sub) {
2541 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002542 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002543 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002544 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002545 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002546
Chris Lattner50af16a2004-11-13 19:50:12 +00002547 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002548 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002549 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002550 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002551
Chris Lattner50af16a2004-11-13 19:50:12 +00002552 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002553 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002554 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002555 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002556 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002557}
2558
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002559Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2560 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2561
2562 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002563 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002564 return BinaryOperator::CreateFAdd(Op0, V);
2565
2566 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2567 if (Op1I->getOpcode() == Instruction::FAdd) {
2568 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002569 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002570 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002571 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002572 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002573 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002574 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002575 }
2576
2577 return 0;
2578}
2579
Chris Lattnera0141b92007-07-15 20:42:37 +00002580/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2581/// comparison only checks the sign bit. If it only checks the sign bit, set
2582/// TrueIfSigned if the result of the comparison is true when the input value is
2583/// signed.
2584static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2585 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002586 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002587 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2588 TrueIfSigned = true;
2589 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002590 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2591 TrueIfSigned = true;
2592 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002593 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2594 TrueIfSigned = false;
2595 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002596 case ICmpInst::ICMP_UGT:
2597 // True if LHS u> RHS and RHS == high-bit-mask - 1
2598 TrueIfSigned = true;
2599 return RHS->getValue() ==
2600 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2601 case ICmpInst::ICMP_UGE:
2602 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2603 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002604 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002605 default:
2606 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002607 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002608}
2609
Chris Lattner7e708292002-06-25 16:13:24 +00002610Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002611 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002612 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002613
Eli Friedman1694e092009-07-18 09:12:15 +00002614 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002615 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002616
Chris Lattner233f7dc2002-08-12 21:17:25 +00002617 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002618 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2619 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002620
2621 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002622 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002623 if (SI->getOpcode() == Instruction::Shl)
2624 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002625 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002626 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002627
Zhou Sheng843f07672007-04-19 05:39:12 +00002628 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002629 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2630 if (CI->equalsInt(1)) // X * 1 == X
2631 return ReplaceInstUsesWith(I, Op0);
2632 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002633 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002634
Zhou Sheng97b52c22007-03-29 01:57:21 +00002635 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002636 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002637 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002638 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002639 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002640 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002641 if (Op1->isNullValue())
2642 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002643
2644 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2645 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002646 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002647
2648 // As above, vector X*splat(1.0) -> X in all defined cases.
2649 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002650 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2651 if (CI->equalsInt(1))
2652 return ReplaceInstUsesWith(I, Op0);
2653 }
2654 }
Chris Lattnera2881962003-02-18 19:28:33 +00002655 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002656
2657 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2658 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002659 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002660 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002661 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002662 Op1, "tmp");
2663 InsertNewInstBefore(Add, I);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002664 Value *C1C2 = ConstantExpr::getMul(Op1,
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002665 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002666 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002667
2668 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002669
2670 // Try to fold constant mul into select arguments.
2671 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002672 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002673 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002674
2675 if (isa<PHINode>(Op0))
2676 if (Instruction *NV = FoldOpIntoPhi(I))
2677 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002678 }
2679
Dan Gohman186a6362009-08-12 16:04:34 +00002680 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2681 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002682 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002683
Nick Lewycky0c730792008-11-21 07:33:58 +00002684 // (X / Y) * Y = X - (X % Y)
2685 // (X / Y) * -Y = (X % Y) - X
2686 {
2687 Value *Op1 = I.getOperand(1);
2688 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2689 if (!BO ||
2690 (BO->getOpcode() != Instruction::UDiv &&
2691 BO->getOpcode() != Instruction::SDiv)) {
2692 Op1 = Op0;
2693 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2694 }
Dan Gohman186a6362009-08-12 16:04:34 +00002695 Value *Neg = dyn_castNegVal(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002696 if (BO && BO->hasOneUse() &&
2697 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2698 (BO->getOpcode() == Instruction::UDiv ||
2699 BO->getOpcode() == Instruction::SDiv)) {
2700 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2701
Dan Gohmanfa94b942009-08-12 16:33:09 +00002702 // If the division is exact, X % Y is zero.
2703 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2704 if (SDiv->isExact()) {
2705 if (Op1BO == Op1)
2706 return ReplaceInstUsesWith(I, Op0BO);
2707 else
2708 return BinaryOperator::CreateNeg(Op0BO);
2709 }
2710
Nick Lewycky0c730792008-11-21 07:33:58 +00002711 Instruction *Rem;
2712 if (BO->getOpcode() == Instruction::UDiv)
2713 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2714 else
2715 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2716
2717 InsertNewInstBefore(Rem, I);
2718 Rem->takeName(BO);
2719
2720 if (Op1BO == Op1)
2721 return BinaryOperator::CreateSub(Op0BO, Rem);
2722 else
2723 return BinaryOperator::CreateSub(Rem, Op0BO);
2724 }
2725 }
2726
Owen Anderson1d0be152009-08-13 21:58:54 +00002727 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002728 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2729
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002730 // If one of the operands of the multiply is a cast from a boolean value, then
2731 // we know the bool is either zero or one, so this is a 'masking' multiply.
2732 // See if we can simplify things based on how the boolean was originally
2733 // formed.
2734 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002735 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Owen Anderson1d0be152009-08-13 21:58:54 +00002736 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002737 BoolCast = CI;
2738 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002739 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00002740 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002741 BoolCast = CI;
2742 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002743 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002744 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2745 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002746 bool TIS = false;
2747
Reid Spencere4d87aa2006-12-23 06:05:41 +00002748 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002749 // multiply into a shift/and combination.
2750 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002751 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2752 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002753 // Shift the X value right to turn it into "all signbits".
Owen Andersoneed707b2009-07-24 23:12:02 +00002754 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002755 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002756 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002757 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002758 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002759 BoolCast->getOperand(0)->getName()+
2760 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002761
2762 // If the multiply type is not the same as the source type, sign extend
2763 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002764 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002765 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2766 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002767 Instruction::CastOps opcode =
2768 (SrcBits == DstBits ? Instruction::BitCast :
2769 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2770 V = InsertCastBefore(opcode, V, I.getType(), I);
2771 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002772
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002773 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002774 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002775 }
2776 }
2777 }
2778
Chris Lattner7e708292002-06-25 16:13:24 +00002779 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002780}
2781
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002782Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2783 bool Changed = SimplifyCommutative(I);
2784 Value *Op0 = I.getOperand(0);
2785
2786 // Simplify mul instructions with a constant RHS...
2787 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2788 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2789 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2790 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2791 if (Op1F->isExactlyValue(1.0))
2792 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2793 } else if (isa<VectorType>(Op1->getType())) {
2794 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2795 // As above, vector X*splat(1.0) -> X in all defined cases.
2796 if (Constant *Splat = Op1V->getSplatValue()) {
2797 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2798 if (F->isExactlyValue(1.0))
2799 return ReplaceInstUsesWith(I, Op0);
2800 }
2801 }
2802 }
2803
2804 // Try to fold constant mul into select arguments.
2805 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2806 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2807 return R;
2808
2809 if (isa<PHINode>(Op0))
2810 if (Instruction *NV = FoldOpIntoPhi(I))
2811 return NV;
2812 }
2813
Dan Gohman186a6362009-08-12 16:04:34 +00002814 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2815 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002816 return BinaryOperator::CreateFMul(Op0v, Op1v);
2817
2818 return Changed ? &I : 0;
2819}
2820
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002821/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2822/// instruction.
2823bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2824 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2825
2826 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2827 int NonNullOperand = -1;
2828 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2829 if (ST->isNullValue())
2830 NonNullOperand = 2;
2831 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2832 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2833 if (ST->isNullValue())
2834 NonNullOperand = 1;
2835
2836 if (NonNullOperand == -1)
2837 return false;
2838
2839 Value *SelectCond = SI->getOperand(0);
2840
2841 // Change the div/rem to use 'Y' instead of the select.
2842 I.setOperand(1, SI->getOperand(NonNullOperand));
2843
2844 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2845 // problem. However, the select, or the condition of the select may have
2846 // multiple uses. Based on our knowledge that the operand must be non-zero,
2847 // propagate the known value for the select into other uses of it, and
2848 // propagate a known value of the condition into its other users.
2849
2850 // If the select and condition only have a single use, don't bother with this,
2851 // early exit.
2852 if (SI->use_empty() && SelectCond->hasOneUse())
2853 return true;
2854
2855 // Scan the current block backward, looking for other uses of SI.
2856 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2857
2858 while (BBI != BBFront) {
2859 --BBI;
2860 // If we found a call to a function, we can't assume it will return, so
2861 // information from below it cannot be propagated above it.
2862 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2863 break;
2864
2865 // Replace uses of the select or its condition with the known values.
2866 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2867 I != E; ++I) {
2868 if (*I == SI) {
2869 *I = SI->getOperand(NonNullOperand);
2870 AddToWorkList(BBI);
2871 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002872 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2873 ConstantInt::getFalse(*Context);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002874 AddToWorkList(BBI);
2875 }
2876 }
2877
2878 // If we past the instruction, quit looking for it.
2879 if (&*BBI == SI)
2880 SI = 0;
2881 if (&*BBI == SelectCond)
2882 SelectCond = 0;
2883
2884 // If we ran out of things to eliminate, break out of the loop.
2885 if (SelectCond == 0 && SI == 0)
2886 break;
2887
2888 }
2889 return true;
2890}
2891
2892
Reid Spencer1628cec2006-10-26 06:15:43 +00002893/// This function implements the transforms on div instructions that work
2894/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2895/// used by the visitors to those instructions.
2896/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002897Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002898 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002899
Chris Lattner50b2ca42008-02-19 06:12:18 +00002900 // undef / X -> 0 for integer.
2901 // undef / X -> undef for FP (the undef could be a snan).
2902 if (isa<UndefValue>(Op0)) {
2903 if (Op0->getType()->isFPOrFPVector())
2904 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002905 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002906 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002907
2908 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002909 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002910 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002911
Reid Spencer1628cec2006-10-26 06:15:43 +00002912 return 0;
2913}
Misha Brukmanfd939082005-04-21 23:48:37 +00002914
Reid Spencer1628cec2006-10-26 06:15:43 +00002915/// This function implements the transforms common to both integer division
2916/// instructions (udiv and sdiv). It is called by the visitors to those integer
2917/// division instructions.
2918/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002919Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002920 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2921
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002922 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002923 if (Op0 == Op1) {
2924 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002925 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002926 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00002927 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002928 }
2929
Owen Andersoneed707b2009-07-24 23:12:02 +00002930 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002931 return ReplaceInstUsesWith(I, CI);
2932 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002933
Reid Spencer1628cec2006-10-26 06:15:43 +00002934 if (Instruction *Common = commonDivTransforms(I))
2935 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002936
2937 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2938 // This does not apply for fdiv.
2939 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2940 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002941
2942 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2943 // div X, 1 == X
2944 if (RHS->equalsInt(1))
2945 return ReplaceInstUsesWith(I, Op0);
2946
2947 // (X / C1) / C2 -> X / (C1*C2)
2948 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2949 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2950 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002951 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00002952 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00002953 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002954 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002955 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002956 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002957 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002958
Reid Spencerbca0e382007-03-23 20:05:17 +00002959 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002960 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2961 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2962 return R;
2963 if (isa<PHINode>(Op0))
2964 if (Instruction *NV = FoldOpIntoPhi(I))
2965 return NV;
2966 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002967 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002968
Chris Lattnera2881962003-02-18 19:28:33 +00002969 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002970 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002971 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00002972 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002973
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002974 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00002975 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002976 return ReplaceInstUsesWith(I, Op0);
2977
Nick Lewycky895f0852008-11-27 20:21:08 +00002978 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2979 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2980 // div X, 1 == X
2981 if (X->isOne())
2982 return ReplaceInstUsesWith(I, Op0);
2983 }
2984
Reid Spencer1628cec2006-10-26 06:15:43 +00002985 return 0;
2986}
2987
2988Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2989 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2990
2991 // Handle the integer div common cases
2992 if (Instruction *Common = commonIDivTransforms(I))
2993 return Common;
2994
Reid Spencer1628cec2006-10-26 06:15:43 +00002995 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00002996 // X udiv C^2 -> X >> C
2997 // Check to see if this is an unsigned division with an exact power of 2,
2998 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00002999 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003000 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003001 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003002
3003 // X udiv C, where C >= signbit
3004 if (C->getValue().isNegative()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003005 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky8ca52482008-11-27 22:41:10 +00003006 I);
Owen Andersona7235ea2009-07-31 20:28:14 +00003007 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003008 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003009 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003010 }
3011
3012 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003013 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003014 if (RHSI->getOpcode() == Instruction::Shl &&
3015 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003016 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003017 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003018 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003019 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003020 if (uint32_t C2 = C1.logBase2()) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003021 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003022 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003023 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003024 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003025 }
3026 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003027 }
3028
Reid Spencer1628cec2006-10-26 06:15:43 +00003029 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3030 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003031 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003032 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003033 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003034 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003035 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003036 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003037 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003038 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003039 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003040 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003041 Op0, TC, SI->getName()+".t");
3042 TSI = InsertNewInstBefore(TSI, I);
3043
3044 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003045 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003046 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003047 Op0, FC, SI->getName()+".f");
3048 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003049
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003050 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003051 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003052 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003053 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003054 return 0;
3055}
3056
Reid Spencer1628cec2006-10-26 06:15:43 +00003057Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3058 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3059
3060 // Handle the integer div common cases
3061 if (Instruction *Common = commonIDivTransforms(I))
3062 return Common;
3063
3064 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3065 // sdiv X, -1 == -X
3066 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003067 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003068
Dan Gohmanfa94b942009-08-12 16:33:09 +00003069 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003070 if (cast<SDivOperator>(&I)->isExact() &&
3071 RHS->getValue().isNonNegative() &&
3072 RHS->getValue().isPowerOf2()) {
3073 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3074 RHS->getValue().exactLogBase2());
3075 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3076 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003077
3078 // -X/C --> X/-C provided the negation doesn't overflow.
3079 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3080 if (isa<Constant>(Sub->getOperand(0)) &&
3081 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003082 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003083 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3084 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003085 }
3086
3087 // If the sign bits of both operands are zero (i.e. we can prove they are
3088 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003089 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003090 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003091 if (MaskedValueIsZero(Op0, Mask)) {
3092 if (MaskedValueIsZero(Op1, Mask)) {
3093 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3094 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3095 }
3096 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003097 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003098 ShiftedInt->getValue().isPowerOf2()) {
3099 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3100 // Safe because the only negative value (1 << Y) can take on is
3101 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3102 // the sign bit set.
3103 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3104 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003105 }
Eli Friedman8be17392009-07-18 09:53:21 +00003106 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003107
3108 return 0;
3109}
3110
3111Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3112 return commonDivTransforms(I);
3113}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003114
Reid Spencer0a783f72006-11-02 01:53:59 +00003115/// This function implements the transforms on rem instructions that work
3116/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3117/// is used by the visitors to those instructions.
3118/// @brief Transforms common to all three rem instructions
3119Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003120 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003121
Chris Lattner50b2ca42008-02-19 06:12:18 +00003122 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3123 if (I.getType()->isFPOrFPVector())
3124 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003125 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003126 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003127 if (isa<UndefValue>(Op1))
3128 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003129
3130 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003131 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3132 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003133
Reid Spencer0a783f72006-11-02 01:53:59 +00003134 return 0;
3135}
3136
3137/// This function implements the transforms common to both integer remainder
3138/// instructions (urem and srem). It is called by the visitors to those integer
3139/// remainder instructions.
3140/// @brief Common integer remainder transforms
3141Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3142 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3143
3144 if (Instruction *common = commonRemTransforms(I))
3145 return common;
3146
Dale Johannesened6af242009-01-21 00:35:19 +00003147 // 0 % X == 0 for integer, we don't need to preserve faults!
3148 if (Constant *LHS = dyn_cast<Constant>(Op0))
3149 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003150 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003151
Chris Lattner857e8cd2004-12-12 21:48:58 +00003152 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003153 // X % 0 == undef, we don't need to preserve faults!
3154 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003155 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003156
Chris Lattnera2881962003-02-18 19:28:33 +00003157 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003158 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003159
Chris Lattner97943922006-02-28 05:49:21 +00003160 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3161 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3162 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3163 return R;
3164 } else if (isa<PHINode>(Op0I)) {
3165 if (Instruction *NV = FoldOpIntoPhi(I))
3166 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003167 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003168
3169 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003170 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003171 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003172 }
Chris Lattnera2881962003-02-18 19:28:33 +00003173 }
3174
Reid Spencer0a783f72006-11-02 01:53:59 +00003175 return 0;
3176}
3177
3178Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3179 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3180
3181 if (Instruction *common = commonIRemTransforms(I))
3182 return common;
3183
3184 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3185 // X urem C^2 -> X and C
3186 // Check to see if this is an unsigned remainder with an exact power of 2,
3187 // if so, convert to a bitwise and.
3188 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003189 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003190 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003191 }
3192
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003193 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003194 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3195 if (RHSI->getOpcode() == Instruction::Shl &&
3196 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003197 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003198 Constant *N1 = Constant::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003199 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003200 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003201 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003202 }
3203 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003204 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003205
Reid Spencer0a783f72006-11-02 01:53:59 +00003206 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3207 // where C1&C2 are powers of two.
3208 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3209 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3210 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3211 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003212 if ((STO->getValue().isPowerOf2()) &&
3213 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003214 Value *TrueAnd = InsertNewInstBefore(
Dan Gohman186a6362009-08-12 16:04:34 +00003215 BinaryOperator::CreateAnd(Op0, SubOne(STO),
Owen Andersond672ecb2009-07-03 00:17:18 +00003216 SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003217 Value *FalseAnd = InsertNewInstBefore(
Dan Gohman186a6362009-08-12 16:04:34 +00003218 BinaryOperator::CreateAnd(Op0, SubOne(SFO),
Owen Andersond672ecb2009-07-03 00:17:18 +00003219 SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003220 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003221 }
3222 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003223 }
3224
Chris Lattner3f5b8772002-05-06 16:14:14 +00003225 return 0;
3226}
3227
Reid Spencer0a783f72006-11-02 01:53:59 +00003228Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3229 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3230
Dan Gohmancff55092007-11-05 23:16:33 +00003231 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003232 if (Instruction *common = commonIRemTransforms(I))
3233 return common;
3234
Dan Gohman186a6362009-08-12 16:04:34 +00003235 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003236 if (!isa<Constant>(RHSNeg) ||
3237 (isa<ConstantInt>(RHSNeg) &&
3238 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003239 // X % -Y -> X % Y
3240 AddUsesToWorkList(I);
3241 I.setOperand(1, RHSNeg);
3242 return &I;
3243 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003244
Dan Gohmancff55092007-11-05 23:16:33 +00003245 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003246 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003247 if (I.getType()->isInteger()) {
3248 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3249 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3250 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003251 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003252 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003253 }
3254
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003255 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003256 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3257 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003258
Nick Lewycky9dce8732008-12-20 16:48:00 +00003259 bool hasNegative = false;
3260 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3261 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3262 if (RHS->getValue().isNegative())
3263 hasNegative = true;
3264
3265 if (hasNegative) {
3266 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003267 for (unsigned i = 0; i != VWidth; ++i) {
3268 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3269 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003270 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003271 else
3272 Elts[i] = RHS;
3273 }
3274 }
3275
Owen Andersonaf7ec972009-07-28 21:19:26 +00003276 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003277 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003278 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003279 I.setOperand(1, NewRHSV);
3280 return &I;
3281 }
3282 }
3283 }
3284
Reid Spencer0a783f72006-11-02 01:53:59 +00003285 return 0;
3286}
3287
3288Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003289 return commonRemTransforms(I);
3290}
3291
Chris Lattner457dd822004-06-09 07:59:58 +00003292// isOneBitSet - Return true if there is exactly one bit set in the specified
3293// constant.
3294static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003295 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003296}
3297
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003298// isHighOnes - Return true if the constant is of the form 1+0+.
3299// This is the same as lowones(~X).
3300static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003301 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003302}
3303
Reid Spencere4d87aa2006-12-23 06:05:41 +00003304/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003305/// are carefully arranged to allow folding of expressions such as:
3306///
3307/// (A < B) | (A > B) --> (A != B)
3308///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003309/// Note that this is only valid if the first and second predicates have the
3310/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003311///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003312/// Three bits are used to represent the condition, as follows:
3313/// 0 A > B
3314/// 1 A == B
3315/// 2 A < B
3316///
3317/// <=> Value Definition
3318/// 000 0 Always false
3319/// 001 1 A > B
3320/// 010 2 A == B
3321/// 011 3 A >= B
3322/// 100 4 A < B
3323/// 101 5 A != B
3324/// 110 6 A <= B
3325/// 111 7 Always true
3326///
3327static unsigned getICmpCode(const ICmpInst *ICI) {
3328 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003329 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003330 case ICmpInst::ICMP_UGT: return 1; // 001
3331 case ICmpInst::ICMP_SGT: return 1; // 001
3332 case ICmpInst::ICMP_EQ: return 2; // 010
3333 case ICmpInst::ICMP_UGE: return 3; // 011
3334 case ICmpInst::ICMP_SGE: return 3; // 011
3335 case ICmpInst::ICMP_ULT: return 4; // 100
3336 case ICmpInst::ICMP_SLT: return 4; // 100
3337 case ICmpInst::ICMP_NE: return 5; // 101
3338 case ICmpInst::ICMP_ULE: return 6; // 110
3339 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003340 // True -> 7
3341 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003342 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003343 return 0;
3344 }
3345}
3346
Evan Cheng8db90722008-10-14 17:15:11 +00003347/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3348/// predicate into a three bit mask. It also returns whether it is an ordered
3349/// predicate by reference.
3350static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3351 isOrdered = false;
3352 switch (CC) {
3353 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3354 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003355 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3356 case FCmpInst::FCMP_UGT: return 1; // 001
3357 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3358 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003359 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3360 case FCmpInst::FCMP_UGE: return 3; // 011
3361 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3362 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003363 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3364 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003365 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3366 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003367 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003368 default:
3369 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003370 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003371 return 0;
3372 }
3373}
3374
Reid Spencere4d87aa2006-12-23 06:05:41 +00003375/// getICmpValue - This is the complement of getICmpCode, which turns an
3376/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003377/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003378/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003379static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003380 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003381 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003382 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003383 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003384 case 1:
3385 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003386 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003387 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003388 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3389 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003390 case 3:
3391 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003392 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003393 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003394 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003395 case 4:
3396 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003397 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003398 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003399 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3400 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003401 case 6:
3402 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003403 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003404 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003405 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003406 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003407 }
3408}
3409
Evan Cheng8db90722008-10-14 17:15:11 +00003410/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3411/// opcode and two operands into either a FCmp instruction. isordered is passed
3412/// in to determine which kind of predicate to use in the new fcmp instruction.
3413static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003414 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003415 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003416 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003417 case 0:
3418 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003419 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003420 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003421 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003422 case 1:
3423 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003424 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003425 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003426 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003427 case 2:
3428 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003429 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003430 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003431 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003432 case 3:
3433 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003434 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003435 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003436 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003437 case 4:
3438 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003439 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003440 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003441 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003442 case 5:
3443 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003444 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003445 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003446 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003447 case 6:
3448 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003449 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003450 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003451 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003452 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003453 }
3454}
3455
Chris Lattnerb9553d62008-11-16 04:55:20 +00003456/// PredicatesFoldable - Return true if both predicates match sign or if at
3457/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003458static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3459 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003460 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3461 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003462}
3463
3464namespace {
3465// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3466struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003467 InstCombiner &IC;
3468 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003469 ICmpInst::Predicate pred;
3470 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3471 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3472 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003473 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003474 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3475 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003476 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3477 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003478 return false;
3479 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003480 Instruction *apply(Instruction &Log) const {
3481 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3482 if (ICI->getOperand(0) != LHS) {
3483 assert(ICI->getOperand(1) == LHS);
3484 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003485 }
3486
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003487 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003488 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003489 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003490 unsigned Code;
3491 switch (Log.getOpcode()) {
3492 case Instruction::And: Code = LHSCode & RHSCode; break;
3493 case Instruction::Or: Code = LHSCode | RHSCode; break;
3494 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003495 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003496 }
3497
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003498 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3499 ICmpInst::isSignedPredicate(ICI->getPredicate());
3500
Owen Andersond672ecb2009-07-03 00:17:18 +00003501 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003502 if (Instruction *I = dyn_cast<Instruction>(RV))
3503 return I;
3504 // Otherwise, it's a constant boolean value...
3505 return IC.ReplaceInstUsesWith(Log, RV);
3506 }
3507};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003508} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003509
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003510// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3511// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003512// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003513Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003514 ConstantInt *OpRHS,
3515 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003516 BinaryOperator &TheAnd) {
3517 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003518 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003519 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003520 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003521
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003522 switch (Op->getOpcode()) {
3523 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003524 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003525 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003526 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003527 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003528 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003529 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003530 }
3531 break;
3532 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003533 if (Together == AndRHS) // (X | C) & C --> C
3534 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003535
Chris Lattner6e7ba452005-01-01 16:22:27 +00003536 if (Op->hasOneUse() && Together != OpRHS) {
3537 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003538 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003539 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003540 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003541 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003542 }
3543 break;
3544 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003545 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003546 // Adding a one to a single bit bit-field should be turned into an XOR
3547 // of the bit. First thing to check is to see if this AND is with a
3548 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003549 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003550
3551 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003552 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003553 // Ok, at this point, we know that we are masking the result of the
3554 // ADD down to exactly one bit. If the constant we are adding has
3555 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003556 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003557
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003558 // Check to see if any bits below the one bit set in AndRHSV are set.
3559 if ((AddRHS & (AndRHSV-1)) == 0) {
3560 // If not, the only thing that can effect the output of the AND is
3561 // the bit specified by AndRHSV. If that bit is set, the effect of
3562 // the XOR is to toggle the bit. If it is clear, then the ADD has
3563 // no effect.
3564 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3565 TheAnd.setOperand(0, X);
3566 return &TheAnd;
3567 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003568 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003569 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003570 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003571 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003572 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003573 }
3574 }
3575 }
3576 }
3577 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003578
3579 case Instruction::Shl: {
3580 // We know that the AND will not produce any of the bits shifted in, so if
3581 // the anded constant includes them, clear them now!
3582 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003583 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003584 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003585 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003586 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003587
Zhou Sheng290bec52007-03-29 08:15:12 +00003588 if (CI->getValue() == ShlMask) {
3589 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003590 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3591 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003592 TheAnd.setOperand(1, CI);
3593 return &TheAnd;
3594 }
3595 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003596 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003597 case Instruction::LShr:
3598 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003599 // We know that the AND will not produce any of the bits shifted in, so if
3600 // the anded constant includes them, clear them now! This only applies to
3601 // unsigned shifts, because a signed shr may bring in set bits!
3602 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003603 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003604 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003605 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003606 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003607
Zhou Sheng290bec52007-03-29 08:15:12 +00003608 if (CI->getValue() == ShrMask) {
3609 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003610 return ReplaceInstUsesWith(TheAnd, Op);
3611 } else if (CI != AndRHS) {
3612 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3613 return &TheAnd;
3614 }
3615 break;
3616 }
3617 case Instruction::AShr:
3618 // Signed shr.
3619 // See if this is shifting in some sign extension, then masking it out
3620 // with an and.
3621 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003622 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003623 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003624 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003625 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003626 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003627 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003628 // Make the argument unsigned.
3629 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003630 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003631 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003632 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003633 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003634 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003635 }
3636 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003637 }
3638 return 0;
3639}
3640
Chris Lattner8b170942002-08-09 23:47:40 +00003641
Chris Lattnera96879a2004-09-29 17:40:11 +00003642/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3643/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003644/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3645/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003646/// insert new instructions.
3647Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003648 bool isSigned, bool Inside,
3649 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003650 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003651 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003652 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003653
Chris Lattnera96879a2004-09-29 17:40:11 +00003654 if (Inside) {
3655 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003656 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003657
Reid Spencere4d87aa2006-12-23 06:05:41 +00003658 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003659 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003660 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003661 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003662 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003663 }
3664
3665 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003666 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003667 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003668 InsertNewInstBefore(Add, IB);
Owen Andersonbaf3c402009-07-29 18:55:55 +00003669 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003670 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003671 }
3672
3673 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003674 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003675
Reid Spencere4e40032007-03-21 23:19:50 +00003676 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003677 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003678 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003679 ICmpInst::Predicate pred = (isSigned ?
3680 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003681 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003682 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003683
Reid Spencere4e40032007-03-21 23:19:50 +00003684 // Emit V-Lo >u Hi-1-Lo
3685 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003686 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003687 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003688 InsertNewInstBefore(Add, IB);
Owen Andersonbaf3c402009-07-29 18:55:55 +00003689 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003690 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003691}
3692
Chris Lattner7203e152005-09-18 07:22:02 +00003693// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3694// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3695// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3696// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003697static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003698 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003699 uint32_t BitWidth = Val->getType()->getBitWidth();
3700 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003701
3702 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003703 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003704 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003705 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003706 return true;
3707}
3708
Chris Lattner7203e152005-09-18 07:22:02 +00003709/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3710/// where isSub determines whether the operator is a sub. If we can fold one of
3711/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003712///
3713/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3714/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3715/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3716///
3717/// return (A +/- B).
3718///
3719Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003720 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003721 Instruction &I) {
3722 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3723 if (!LHSI || LHSI->getNumOperands() != 2 ||
3724 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3725
3726 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3727
3728 switch (LHSI->getOpcode()) {
3729 default: return 0;
3730 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003731 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003732 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003733 if ((Mask->getValue().countLeadingZeros() +
3734 Mask->getValue().countPopulation()) ==
3735 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003736 break;
3737
3738 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3739 // part, we don't need any explicit masks to take them out of A. If that
3740 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003741 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003742 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003743 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003744 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003745 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003746 break;
3747 }
3748 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003749 return 0;
3750 case Instruction::Or:
3751 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003752 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003753 if ((Mask->getValue().countLeadingZeros() +
3754 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003755 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003756 break;
3757 return 0;
3758 }
3759
3760 Instruction *New;
3761 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003762 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003763 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003764 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003765 return InsertNewInstBefore(New, I);
3766}
3767
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003768/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3769Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3770 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003771 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003772 ConstantInt *LHSCst, *RHSCst;
3773 ICmpInst::Predicate LHSCC, RHSCC;
3774
Chris Lattnerea065fb2008-11-16 05:10:52 +00003775 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003776 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003777 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003778 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003779 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003780 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003781
3782 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3783 // where C is a power of 2
3784 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3785 LHSCst->getValue().isPowerOf2()) {
3786 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3787 InsertNewInstBefore(NewOr, I);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003788 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003789 }
3790
3791 // From here on, we only handle:
3792 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3793 if (Val != Val2) return 0;
3794
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003795 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3796 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3797 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3798 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3799 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3800 return 0;
3801
3802 // We can't fold (ugt x, C) & (sgt x, C2).
3803 if (!PredicatesFoldable(LHSCC, RHSCC))
3804 return 0;
3805
3806 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003807 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003808 if (ICmpInst::isSignedPredicate(LHSCC) ||
3809 (ICmpInst::isEquality(LHSCC) &&
3810 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003811 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003812 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003813 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3814
3815 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003816 std::swap(LHS, RHS);
3817 std::swap(LHSCst, RHSCst);
3818 std::swap(LHSCC, RHSCC);
3819 }
3820
3821 // At this point, we know we have have two icmp instructions
3822 // comparing a value against two constants and and'ing the result
3823 // together. Because of the above check, we know that we only have
3824 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3825 // (from the FoldICmpLogical check above), that the two constants
3826 // are not equal and that the larger constant is on the RHS
3827 assert(LHSCst != RHSCst && "Compares not folded above?");
3828
3829 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003830 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003831 case ICmpInst::ICMP_EQ:
3832 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003833 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003834 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3835 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3836 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003837 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003838 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3839 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3840 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3841 return ReplaceInstUsesWith(I, LHS);
3842 }
3843 case ICmpInst::ICMP_NE:
3844 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003845 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003846 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003847 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003848 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003849 break; // (X != 13 & X u< 15) -> no change
3850 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003851 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003852 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003853 break; // (X != 13 & X s< 15) -> no change
3854 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3855 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3856 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3857 return ReplaceInstUsesWith(I, RHS);
3858 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003859 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003860 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003861 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3862 Val->getName()+".off");
3863 InsertNewInstBefore(Add, I);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003864 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003865 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003866 }
3867 break; // (X != 13 & X != 15) -> no change
3868 }
3869 break;
3870 case ICmpInst::ICMP_ULT:
3871 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003872 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003873 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3874 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003875 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003876 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3877 break;
3878 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3879 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3880 return ReplaceInstUsesWith(I, LHS);
3881 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3882 break;
3883 }
3884 break;
3885 case ICmpInst::ICMP_SLT:
3886 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003887 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003888 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3889 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003890 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003891 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3892 break;
3893 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3894 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3895 return ReplaceInstUsesWith(I, LHS);
3896 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3897 break;
3898 }
3899 break;
3900 case ICmpInst::ICMP_UGT:
3901 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003902 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003903 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3904 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3905 return ReplaceInstUsesWith(I, RHS);
3906 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3907 break;
3908 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003909 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003910 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003911 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003912 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003913 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003914 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003915 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3916 break;
3917 }
3918 break;
3919 case ICmpInst::ICMP_SGT:
3920 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003921 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003922 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3923 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3924 return ReplaceInstUsesWith(I, RHS);
3925 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3926 break;
3927 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003928 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003929 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003930 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003931 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003932 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003933 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003934 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3935 break;
3936 }
3937 break;
3938 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003939
3940 return 0;
3941}
3942
Chris Lattner42d1be02009-07-23 05:14:02 +00003943Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3944 FCmpInst *RHS) {
3945
3946 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3947 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3948 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3949 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3950 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3951 // If either of the constants are nans, then the whole thing returns
3952 // false.
3953 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00003954 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003955 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00003956 LHS->getOperand(0), RHS->getOperand(0));
3957 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003958
3959 // Handle vector zeros. This occurs because the canonical form of
3960 // "fcmp ord x,x" is "fcmp ord x, 0".
3961 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3962 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003963 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00003964 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00003965 return 0;
3966 }
3967
3968 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3969 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3970 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3971
3972
3973 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3974 // Swap RHS operands to match LHS.
3975 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3976 std::swap(Op1LHS, Op1RHS);
3977 }
3978
3979 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3980 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3981 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003982 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00003983
3984 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00003985 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003986 if (Op0CC == FCmpInst::FCMP_TRUE)
3987 return ReplaceInstUsesWith(I, RHS);
3988 if (Op1CC == FCmpInst::FCMP_TRUE)
3989 return ReplaceInstUsesWith(I, LHS);
3990
3991 bool Op0Ordered;
3992 bool Op1Ordered;
3993 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3994 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3995 if (Op1Pred == 0) {
3996 std::swap(LHS, RHS);
3997 std::swap(Op0Pred, Op1Pred);
3998 std::swap(Op0Ordered, Op1Ordered);
3999 }
4000 if (Op0Pred == 0) {
4001 // uno && ueq -> uno && (uno || eq) -> ueq
4002 // ord && olt -> ord && (ord && lt) -> olt
4003 if (Op0Ordered == Op1Ordered)
4004 return ReplaceInstUsesWith(I, RHS);
4005
4006 // uno && oeq -> uno && (ord && eq) -> false
4007 // uno && ord -> false
4008 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004009 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004010 // ord && ueq -> ord && (uno || eq) -> oeq
4011 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4012 Op0LHS, Op0RHS, Context));
4013 }
4014 }
4015
4016 return 0;
4017}
4018
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004019
Chris Lattner7e708292002-06-25 16:13:24 +00004020Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004021 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004022 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004023
Chris Lattnere87597f2004-10-16 18:11:37 +00004024 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004025 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004026
Chris Lattner6e7ba452005-01-01 16:22:27 +00004027 // and X, X = X
4028 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004029 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004030
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004031 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004032 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004033 if (SimplifyDemandedInstructionBits(I))
4034 return &I;
4035 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004036 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004037 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004038 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004039 } else if (isa<ConstantAggregateZero>(Op1)) {
4040 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004041 }
4042 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004043
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004044 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004045 const APInt& AndRHSMask = AndRHS->getValue();
4046 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004047
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004048 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004049 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004050 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004051 Value *Op0LHS = Op0I->getOperand(0);
4052 Value *Op0RHS = Op0I->getOperand(1);
4053 switch (Op0I->getOpcode()) {
4054 case Instruction::Xor:
4055 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004056 // If the mask is only needed on one incoming arm, push it up.
4057 if (Op0I->hasOneUse()) {
4058 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4059 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004060 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004061 Op0RHS->getName()+".masked");
4062 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004063 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004064 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004065 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004066 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004067 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4068 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004069 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004070 Op0LHS->getName()+".masked");
4071 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004072 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004073 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4074 }
4075 }
4076
Chris Lattner6e7ba452005-01-01 16:22:27 +00004077 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004078 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004079 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4080 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4081 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4082 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004083 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004084 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004085 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004086 break;
4087
4088 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004089 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4090 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4091 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4092 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004093 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004094
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004095 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4096 // has 1's for all bits that the subtraction with A might affect.
4097 if (Op0I->hasOneUse()) {
4098 uint32_t BitWidth = AndRHSMask.getBitWidth();
4099 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4100 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4101
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004102 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004103 if (!(A && A->isZero()) && // avoid infinite recursion.
4104 MaskedValueIsZero(Op0LHS, Mask)) {
Dan Gohman4ae51262009-08-12 16:23:25 +00004105 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004106 InsertNewInstBefore(NewNeg, I);
4107 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4108 }
4109 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004110 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004111
4112 case Instruction::Shl:
4113 case Instruction::LShr:
4114 // (1 << x) & 1 --> zext(x == 0)
4115 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004116 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004117 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00004118 Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004119 InsertNewInstBefore(NewICmp, I);
4120 return new ZExtInst(NewICmp, I.getType());
4121 }
4122 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004123 }
4124
Chris Lattner58403262003-07-23 19:25:52 +00004125 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004126 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004127 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004128 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004129 // If this is an integer truncation or change from signed-to-unsigned, and
4130 // if the source is an and/or with immediate, transform it. This
4131 // frequently occurs for bitfield accesses.
4132 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004133 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004134 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004135 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004136 if (CastOp->getOpcode() == Instruction::And) {
4137 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004138 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4139 // This will fold the two constants together, which may allow
4140 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004141 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004142 CastOp->getOperand(0), I.getType(),
4143 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004144 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004145 // trunc_or_bitcast(C1)&C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004146 Constant *C3 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004147 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4148 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004149 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004150 } else if (CastOp->getOpcode() == Instruction::Or) {
4151 // Change: and (cast (or X, C1) to T), C2
4152 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004153 Constant *C3 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004154 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4155 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004156 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004157 return ReplaceInstUsesWith(I, AndRHS);
4158 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004159 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004160 }
Chris Lattner06782f82003-07-23 19:36:21 +00004161 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004162
4163 // Try to fold constant and into select arguments.
4164 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004165 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004166 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004167 if (isa<PHINode>(Op0))
4168 if (Instruction *NV = FoldOpIntoPhi(I))
4169 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004170 }
4171
Dan Gohman186a6362009-08-12 16:04:34 +00004172 Value *Op0NotVal = dyn_castNotVal(Op0);
4173 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004174
Chris Lattner5b62aa72004-06-18 06:07:51 +00004175 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004176 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004177
Misha Brukmancb6267b2004-07-30 12:50:08 +00004178 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004179 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004180 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004181 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004182 InsertNewInstBefore(Or, I);
Dan Gohman4ae51262009-08-12 16:23:25 +00004183 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004184 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004185
4186 {
Chris Lattner003b6202007-06-15 05:58:24 +00004187 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004188 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004189 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4190 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004191
4192 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004193 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004194 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004195 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004196 }
4197 }
4198
Dan Gohman4ae51262009-08-12 16:23:25 +00004199 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004200 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4201 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004202
4203 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004204 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004205 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004206 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004207 }
4208 }
Chris Lattner64daab52006-04-01 08:03:55 +00004209
4210 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004211 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004212 if (A == Op1) { // (A^B)&A -> A&(A^B)
4213 I.swapOperands(); // Simplify below
4214 std::swap(Op0, Op1);
4215 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4216 cast<BinaryOperator>(Op0)->swapOperands();
4217 I.swapOperands(); // Simplify below
4218 std::swap(Op0, Op1);
4219 }
4220 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004221
Chris Lattner64daab52006-04-01 08:03:55 +00004222 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004223 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004224 if (B == Op0) { // B&(A^B) -> B&(B^A)
4225 cast<BinaryOperator>(Op1)->swapOperands();
4226 std::swap(A, B);
4227 }
4228 if (A == Op0) { // A&(A^B) -> A & ~B
Dan Gohman4ae51262009-08-12 16:23:25 +00004229 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004230 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004231 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004232 }
4233 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004234
4235 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004236 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4237 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004238 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004239 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4240 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004241 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004242 }
4243
Reid Spencere4d87aa2006-12-23 06:05:41 +00004244 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4245 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004246 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004247 return R;
4248
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004249 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4250 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4251 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004252 }
4253
Chris Lattner6fc205f2006-05-05 06:39:07 +00004254 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004255 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4256 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4257 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4258 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004259 if (SrcTy == Op1C->getOperand(0)->getType() &&
4260 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004261 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004262 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4263 I.getType(), TD) &&
4264 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4265 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004266 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004267 Op1C->getOperand(0),
4268 I.getName());
4269 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004270 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004271 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004272 }
Chris Lattnere511b742006-11-14 07:46:50 +00004273
4274 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004275 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4276 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4277 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004278 SI0->getOperand(1) == SI1->getOperand(1) &&
4279 (SI0->hasOneUse() || SI1->hasOneUse())) {
4280 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004281 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004282 SI1->getOperand(0),
4283 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004284 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004285 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004286 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004287 }
4288
Evan Cheng8db90722008-10-14 17:15:11 +00004289 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004290 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004291 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4292 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4293 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004294 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004295
Chris Lattner7e708292002-06-25 16:13:24 +00004296 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004297}
4298
Chris Lattner8c34cd22008-10-05 02:13:19 +00004299/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4300/// capable of providing pieces of a bswap. The subexpression provides pieces
4301/// of a bswap if it is proven that each of the non-zero bytes in the output of
4302/// the expression came from the corresponding "byte swapped" byte in some other
4303/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4304/// we know that the expression deposits the low byte of %X into the high byte
4305/// of the bswap result and that all other bytes are zero. This expression is
4306/// accepted, the high byte of ByteValues is set to X to indicate a correct
4307/// match.
4308///
4309/// This function returns true if the match was unsuccessful and false if so.
4310/// On entry to the function the "OverallLeftShift" is a signed integer value
4311/// indicating the number of bytes that the subexpression is later shifted. For
4312/// example, if the expression is later right shifted by 16 bits, the
4313/// OverallLeftShift value would be -2 on entry. This is used to specify which
4314/// byte of ByteValues is actually being set.
4315///
4316/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4317/// byte is masked to zero by a user. For example, in (X & 255), X will be
4318/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4319/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4320/// always in the local (OverallLeftShift) coordinate space.
4321///
4322static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4323 SmallVector<Value*, 8> &ByteValues) {
4324 if (Instruction *I = dyn_cast<Instruction>(V)) {
4325 // If this is an or instruction, it may be an inner node of the bswap.
4326 if (I->getOpcode() == Instruction::Or) {
4327 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4328 ByteValues) ||
4329 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4330 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004331 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004332
4333 // If this is a logical shift by a constant multiple of 8, recurse with
4334 // OverallLeftShift and ByteMask adjusted.
4335 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4336 unsigned ShAmt =
4337 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4338 // Ensure the shift amount is defined and of a byte value.
4339 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4340 return true;
4341
4342 unsigned ByteShift = ShAmt >> 3;
4343 if (I->getOpcode() == Instruction::Shl) {
4344 // X << 2 -> collect(X, +2)
4345 OverallLeftShift += ByteShift;
4346 ByteMask >>= ByteShift;
4347 } else {
4348 // X >>u 2 -> collect(X, -2)
4349 OverallLeftShift -= ByteShift;
4350 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004351 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004352 }
4353
4354 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4355 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4356
4357 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4358 ByteValues);
4359 }
4360
4361 // If this is a logical 'and' with a mask that clears bytes, clear the
4362 // corresponding bytes in ByteMask.
4363 if (I->getOpcode() == Instruction::And &&
4364 isa<ConstantInt>(I->getOperand(1))) {
4365 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4366 unsigned NumBytes = ByteValues.size();
4367 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4368 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4369
4370 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4371 // If this byte is masked out by a later operation, we don't care what
4372 // the and mask is.
4373 if ((ByteMask & (1 << i)) == 0)
4374 continue;
4375
4376 // If the AndMask is all zeros for this byte, clear the bit.
4377 APInt MaskB = AndMask & Byte;
4378 if (MaskB == 0) {
4379 ByteMask &= ~(1U << i);
4380 continue;
4381 }
4382
4383 // If the AndMask is not all ones for this byte, it's not a bytezap.
4384 if (MaskB != Byte)
4385 return true;
4386
4387 // Otherwise, this byte is kept.
4388 }
4389
4390 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4391 ByteValues);
4392 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004393 }
4394
Chris Lattner8c34cd22008-10-05 02:13:19 +00004395 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4396 // the input value to the bswap. Some observations: 1) if more than one byte
4397 // is demanded from this input, then it could not be successfully assembled
4398 // into a byteswap. At least one of the two bytes would not be aligned with
4399 // their ultimate destination.
4400 if (!isPowerOf2_32(ByteMask)) return true;
4401 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004402
Chris Lattner8c34cd22008-10-05 02:13:19 +00004403 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4404 // is demanded, it needs to go into byte 0 of the result. This means that the
4405 // byte needs to be shifted until it lands in the right byte bucket. The
4406 // shift amount depends on the position: if the byte is coming from the high
4407 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4408 // low part, it must be shifted left.
4409 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4410 if (InputByteNo < ByteValues.size()/2) {
4411 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4412 return true;
4413 } else {
4414 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4415 return true;
4416 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004417
4418 // If the destination byte value is already defined, the values are or'd
4419 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004420 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004421 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004422 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004423 return false;
4424}
4425
4426/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4427/// If so, insert the new bswap intrinsic and return it.
4428Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004429 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004430 if (!ITy || ITy->getBitWidth() % 16 ||
4431 // ByteMask only allows up to 32-byte values.
4432 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004433 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004434
4435 /// ByteValues - For each byte of the result, we keep track of which value
4436 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004437 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004438 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004439
4440 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004441 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4442 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004443 return 0;
4444
4445 // Check to see if all of the bytes come from the same value.
4446 Value *V = ByteValues[0];
4447 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4448
4449 // Check to make sure that all of the bytes come from the same value.
4450 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4451 if (ByteValues[i] != V)
4452 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004453 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004454 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004455 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004456 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004457}
4458
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004459/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4460/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4461/// we can simplify this expression to "cond ? C : D or B".
4462static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004463 Value *C, Value *D,
4464 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004465 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004466 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004467 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004468 return 0;
4469
Chris Lattnera6a474d2008-11-16 04:26:55 +00004470 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004471 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004472 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004473 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004474 return SelectInst::Create(Cond, C, B);
4475 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004476 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004477 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004478 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004479 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004480 return 0;
4481}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004482
Chris Lattner69d4ced2008-11-16 05:20:07 +00004483/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4484Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4485 ICmpInst *LHS, ICmpInst *RHS) {
4486 Value *Val, *Val2;
4487 ConstantInt *LHSCst, *RHSCst;
4488 ICmpInst::Predicate LHSCC, RHSCC;
4489
4490 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004491 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004492 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004493 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004494 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004495 return 0;
4496
4497 // From here on, we only handle:
4498 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4499 if (Val != Val2) return 0;
4500
4501 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4502 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4503 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4504 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4505 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4506 return 0;
4507
4508 // We can't fold (ugt x, C) | (sgt x, C2).
4509 if (!PredicatesFoldable(LHSCC, RHSCC))
4510 return 0;
4511
4512 // Ensure that the larger constant is on the RHS.
4513 bool ShouldSwap;
4514 if (ICmpInst::isSignedPredicate(LHSCC) ||
4515 (ICmpInst::isEquality(LHSCC) &&
4516 ICmpInst::isSignedPredicate(RHSCC)))
4517 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4518 else
4519 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4520
4521 if (ShouldSwap) {
4522 std::swap(LHS, RHS);
4523 std::swap(LHSCst, RHSCst);
4524 std::swap(LHSCC, RHSCC);
4525 }
4526
4527 // At this point, we know we have have two icmp instructions
4528 // comparing a value against two constants and or'ing the result
4529 // together. Because of the above check, we know that we only have
4530 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4531 // FoldICmpLogical check above), that the two constants are not
4532 // equal.
4533 assert(LHSCst != RHSCst && "Compares not folded above?");
4534
4535 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004536 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004537 case ICmpInst::ICMP_EQ:
4538 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004539 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004540 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004541 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004542 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004543 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004544 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4545 Val->getName()+".off");
4546 InsertNewInstBefore(Add, I);
Dan Gohman186a6362009-08-12 16:04:34 +00004547 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004548 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004549 }
4550 break; // (X == 13 | X == 15) -> no change
4551 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4552 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4553 break;
4554 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4555 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4556 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4557 return ReplaceInstUsesWith(I, RHS);
4558 }
4559 break;
4560 case ICmpInst::ICMP_NE:
4561 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004562 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004563 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4564 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4565 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4566 return ReplaceInstUsesWith(I, LHS);
4567 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4568 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4569 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004570 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004571 }
4572 break;
4573 case ICmpInst::ICMP_ULT:
4574 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004575 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004576 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4577 break;
4578 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4579 // If RHSCst is [us]MAXINT, it is always false. Not handling
4580 // this can cause overflow.
4581 if (RHSCst->isMaxValue(false))
4582 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004583 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004584 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004585 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4586 break;
4587 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4588 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4589 return ReplaceInstUsesWith(I, RHS);
4590 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4591 break;
4592 }
4593 break;
4594 case ICmpInst::ICMP_SLT:
4595 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004596 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004597 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4598 break;
4599 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4600 // If RHSCst is [us]MAXINT, it is always false. Not handling
4601 // this can cause overflow.
4602 if (RHSCst->isMaxValue(true))
4603 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004604 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004605 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004606 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4607 break;
4608 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4609 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4610 return ReplaceInstUsesWith(I, RHS);
4611 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4612 break;
4613 }
4614 break;
4615 case ICmpInst::ICMP_UGT:
4616 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004617 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004618 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4619 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4620 return ReplaceInstUsesWith(I, LHS);
4621 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4622 break;
4623 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4624 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004625 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004626 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4627 break;
4628 }
4629 break;
4630 case ICmpInst::ICMP_SGT:
4631 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004632 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004633 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4634 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4635 return ReplaceInstUsesWith(I, LHS);
4636 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4637 break;
4638 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4639 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004640 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004641 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4642 break;
4643 }
4644 break;
4645 }
4646 return 0;
4647}
4648
Chris Lattner5414cc52009-07-23 05:46:22 +00004649Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4650 FCmpInst *RHS) {
4651 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4652 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4653 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4654 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4655 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4656 // If either of the constants are nans, then the whole thing returns
4657 // true.
4658 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004659 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004660
4661 // Otherwise, no need to compare the two constants, compare the
4662 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004663 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004664 LHS->getOperand(0), RHS->getOperand(0));
4665 }
4666
4667 // Handle vector zeros. This occurs because the canonical form of
4668 // "fcmp uno x,x" is "fcmp uno x, 0".
4669 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4670 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004671 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004672 LHS->getOperand(0), RHS->getOperand(0));
4673
4674 return 0;
4675 }
4676
4677 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4678 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4679 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4680
4681 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4682 // Swap RHS operands to match LHS.
4683 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4684 std::swap(Op1LHS, Op1RHS);
4685 }
4686 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4687 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4688 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004689 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004690 Op0LHS, Op0RHS);
4691 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004692 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004693 if (Op0CC == FCmpInst::FCMP_FALSE)
4694 return ReplaceInstUsesWith(I, RHS);
4695 if (Op1CC == FCmpInst::FCMP_FALSE)
4696 return ReplaceInstUsesWith(I, LHS);
4697 bool Op0Ordered;
4698 bool Op1Ordered;
4699 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4700 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4701 if (Op0Ordered == Op1Ordered) {
4702 // If both are ordered or unordered, return a new fcmp with
4703 // or'ed predicates.
4704 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4705 Op0LHS, Op0RHS, Context);
4706 if (Instruction *I = dyn_cast<Instruction>(RV))
4707 return I;
4708 // Otherwise, it's a constant boolean value...
4709 return ReplaceInstUsesWith(I, RV);
4710 }
4711 }
4712 return 0;
4713}
4714
Bill Wendlinga698a472008-12-01 08:23:25 +00004715/// FoldOrWithConstants - This helper function folds:
4716///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004717/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004718///
4719/// into:
4720///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004721/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004722///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004723/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004724Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004725 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004726 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4727 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004728
Bill Wendling286a0542008-12-02 06:24:20 +00004729 Value *V1 = 0;
4730 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004731 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004732
Bill Wendling29976b92008-12-02 06:18:11 +00004733 APInt Xor = CI1->getValue() ^ CI2->getValue();
4734 if (!Xor.isAllOnesValue()) return 0;
4735
Bill Wendling286a0542008-12-02 06:24:20 +00004736 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004737 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004738 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4739 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004740 }
4741
4742 return 0;
4743}
4744
Chris Lattner7e708292002-06-25 16:13:24 +00004745Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004746 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004747 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004748
Chris Lattner42593e62007-03-24 23:56:43 +00004749 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004750 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004751
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004752 // or X, X = X
4753 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004754 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004755
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004756 // See if we can simplify any instructions used by the instruction whose sole
4757 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004758 if (SimplifyDemandedInstructionBits(I))
4759 return &I;
4760 if (isa<VectorType>(I.getType())) {
4761 if (isa<ConstantAggregateZero>(Op1)) {
4762 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4763 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4764 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4765 return ReplaceInstUsesWith(I, I.getOperand(1));
4766 }
Chris Lattner42593e62007-03-24 23:56:43 +00004767 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004768
Chris Lattner3f5b8772002-05-06 16:14:14 +00004769 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004770 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004771 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004772 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004773 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004774 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004775 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004776 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004777 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004778 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004779 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004780 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004781
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004782 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004783 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004784 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004785 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004786 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004787 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004788 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004789 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004790 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004791
4792 // Try to fold constant and into select arguments.
4793 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004794 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004795 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004796 if (isa<PHINode>(Op0))
4797 if (Instruction *NV = FoldOpIntoPhi(I))
4798 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004799 }
4800
Chris Lattner4f637d42006-01-06 17:59:59 +00004801 Value *A = 0, *B = 0;
4802 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004803
Dan Gohman4ae51262009-08-12 16:23:25 +00004804 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004805 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4806 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004807 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004808 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4809 return ReplaceInstUsesWith(I, Op0);
4810
Chris Lattner6423d4c2006-07-10 20:25:24 +00004811 // (A | B) | C and A | (B | C) -> bswap if possible.
4812 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004813 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4814 match(Op1, m_Or(m_Value(), m_Value())) ||
4815 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4816 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004817 if (Instruction *BSwap = MatchBSwap(I))
4818 return BSwap;
4819 }
4820
Chris Lattner6e4c6492005-05-09 04:58:36 +00004821 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004822 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004823 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004824 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004825 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004826 InsertNewInstBefore(NOr, I);
4827 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004828 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004829 }
4830
4831 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004832 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004833 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004834 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004835 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004836 InsertNewInstBefore(NOr, I);
4837 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004838 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004839 }
4840
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004841 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004842 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004843 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4844 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004845 Value *V1 = 0, *V2 = 0, *V3 = 0;
4846 C1 = dyn_cast<ConstantInt>(C);
4847 C2 = dyn_cast<ConstantInt>(D);
4848 if (C1 && C2) { // (A & C1)|(B & C2)
4849 // If we have: ((V + N) & C1) | (V & C2)
4850 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4851 // replace with V+N.
4852 if (C1->getValue() == ~C2->getValue()) {
4853 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004854 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004855 // Add commutes, try both ways.
4856 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4857 return ReplaceInstUsesWith(I, A);
4858 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4859 return ReplaceInstUsesWith(I, A);
4860 }
4861 // Or commutes, try both ways.
4862 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004863 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004864 // Add commutes, try both ways.
4865 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4866 return ReplaceInstUsesWith(I, B);
4867 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4868 return ReplaceInstUsesWith(I, B);
4869 }
4870 }
Chris Lattner044e5332007-04-08 08:01:49 +00004871 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004872 }
4873
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004874 // Check to see if we have any common things being and'ed. If so, find the
4875 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004876 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4877 if (A == B) // (A & C)|(A & D) == A & (C|D)
4878 V1 = A, V2 = C, V3 = D;
4879 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4880 V1 = A, V2 = B, V3 = C;
4881 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4882 V1 = C, V2 = A, V3 = D;
4883 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4884 V1 = C, V2 = A, V3 = B;
4885
4886 if (V1) {
4887 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004888 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4889 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004890 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004891 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004892
Dan Gohman1975d032008-10-30 20:40:10 +00004893 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004894 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004895 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004896 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004897 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004898 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004899 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004900 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004901 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004902
Bill Wendlingb01865c2008-11-30 13:52:49 +00004903 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004904 if ((match(C, m_Not(m_Specific(D))) &&
4905 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004906 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004907 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004908 if ((match(A, m_Not(m_Specific(D))) &&
4909 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004910 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004911 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004912 if ((match(C, m_Not(m_Specific(B))) &&
4913 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004914 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004915 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004916 if ((match(A, m_Not(m_Specific(B))) &&
4917 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004918 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004919 }
Chris Lattnere511b742006-11-14 07:46:50 +00004920
4921 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004922 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4923 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4924 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004925 SI0->getOperand(1) == SI1->getOperand(1) &&
4926 (SI0->hasOneUse() || SI1->hasOneUse())) {
4927 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004928 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004929 SI1->getOperand(0),
4930 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004931 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004932 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004933 }
4934 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004935
Bill Wendlingb3833d12008-12-01 01:07:11 +00004936 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004937 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4938 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004939 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004940 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004941 }
4942 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004943 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4944 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004945 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004946 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004947 }
4948
Dan Gohman4ae51262009-08-12 16:23:25 +00004949 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004950 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004951 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004952 } else {
4953 A = 0;
4954 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004955 // Note, A is still live here!
Dan Gohman4ae51262009-08-12 16:23:25 +00004956 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004957 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004958 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004959
Misha Brukmancb6267b2004-07-30 12:50:08 +00004960 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004961 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004962 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004963 I.getName()+".demorgan"), I);
Dan Gohman4ae51262009-08-12 16:23:25 +00004964 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004965 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004966 }
Chris Lattnera2881962003-02-18 19:28:33 +00004967
Reid Spencere4d87aa2006-12-23 06:05:41 +00004968 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4969 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00004970 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004971 return R;
4972
Chris Lattner69d4ced2008-11-16 05:20:07 +00004973 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4974 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4975 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004976 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004977
4978 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004979 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004980 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004981 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004982 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4983 !isa<ICmpInst>(Op1C->getOperand(0))) {
4984 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004985 if (SrcTy == Op1C->getOperand(0)->getType() &&
4986 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00004987 // Only do this if the casts both really cause code to be
4988 // generated.
4989 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4990 I.getType(), TD) &&
4991 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4992 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004993 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004994 Op1C->getOperand(0),
4995 I.getName());
4996 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004997 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004998 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004999 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005000 }
Chris Lattner99c65742007-10-24 05:38:08 +00005001 }
5002
5003
5004 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5005 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005006 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5007 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5008 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005009 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005010
Chris Lattner7e708292002-06-25 16:13:24 +00005011 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005012}
5013
Dan Gohman844731a2008-05-13 00:00:25 +00005014namespace {
5015
Chris Lattnerc317d392004-02-16 01:20:27 +00005016// XorSelf - Implements: X ^ X --> 0
5017struct XorSelf {
5018 Value *RHS;
5019 XorSelf(Value *rhs) : RHS(rhs) {}
5020 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5021 Instruction *apply(BinaryOperator &Xor) const {
5022 return &Xor;
5023 }
5024};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005025
Dan Gohman844731a2008-05-13 00:00:25 +00005026}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005027
Chris Lattner7e708292002-06-25 16:13:24 +00005028Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005029 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005030 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005031
Evan Chengd34af782008-03-25 20:07:13 +00005032 if (isa<UndefValue>(Op1)) {
5033 if (isa<UndefValue>(Op0))
5034 // Handle undef ^ undef -> 0 special case. This is a common
5035 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005036 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005037 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005038 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005039
Chris Lattnerc317d392004-02-16 01:20:27 +00005040 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005041 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005042 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005043 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005044 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005045
5046 // See if we can simplify any instructions used by the instruction whose sole
5047 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005048 if (SimplifyDemandedInstructionBits(I))
5049 return &I;
5050 if (isa<VectorType>(I.getType()))
5051 if (isa<ConstantAggregateZero>(Op1))
5052 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005053
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005054 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005055 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005056 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5057 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5058 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5059 if (Op0I->getOpcode() == Instruction::And ||
5060 Op0I->getOpcode() == Instruction::Or) {
Dan Gohman186a6362009-08-12 16:04:34 +00005061 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5062 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005063 Instruction *NotY =
Dan Gohman4ae51262009-08-12 16:23:25 +00005064 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005065 Op0I->getOperand(1)->getName()+".not");
5066 InsertNewInstBefore(NotY, I);
5067 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005068 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005069 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005070 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005071 }
5072 }
5073 }
5074 }
5075
5076
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005077 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson5defacc2009-07-31 17:39:07 +00005078 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005079 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005080 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005081 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005082 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005083
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005084 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005085 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005086 FCI->getOperand(0), FCI->getOperand(1));
5087 }
5088
Nick Lewycky517e1f52008-05-31 19:01:33 +00005089 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5090 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5091 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5092 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5093 Instruction::CastOps Opcode = Op0C->getOpcode();
5094 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005095 if (RHS == ConstantExpr::getCast(Opcode,
Owen Anderson5defacc2009-07-31 17:39:07 +00005096 ConstantInt::getTrue(*Context),
Nick Lewycky517e1f52008-05-31 19:01:33 +00005097 Op0C->getDestTy())) {
5098 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5099 CI->getOpcode(), CI->getInversePredicate(),
5100 CI->getOperand(0), CI->getOperand(1)), I);
5101 NewCI->takeName(CI);
5102 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5103 }
5104 }
5105 }
5106 }
5107 }
5108
Reid Spencere4d87aa2006-12-23 06:05:41 +00005109 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005110 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005111 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5112 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005113 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5114 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005115 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005116 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005117 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005118
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005119 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005120 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005121 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005122 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005123 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005124 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005125 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005126 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005127 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005128 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005129 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005130 Constant *C = ConstantInt::get(*Context,
5131 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005132 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005133
Chris Lattner7c4049c2004-01-12 19:35:11 +00005134 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005135 } else if (Op0I->getOpcode() == Instruction::Or) {
5136 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005137 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005138 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005139 // Anything in both C1 and C2 is known to be zero, remove it from
5140 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005141 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5142 NewRHS = ConstantExpr::getAnd(NewRHS,
5143 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005144 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005145 I.setOperand(0, Op0I->getOperand(0));
5146 I.setOperand(1, NewRHS);
5147 return &I;
5148 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005149 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005150 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005151 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005152
5153 // Try to fold constant and into select arguments.
5154 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005155 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005156 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005157 if (isa<PHINode>(Op0))
5158 if (Instruction *NV = FoldOpIntoPhi(I))
5159 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005160 }
5161
Dan Gohman186a6362009-08-12 16:04:34 +00005162 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005163 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005164 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005165
Dan Gohman186a6362009-08-12 16:04:34 +00005166 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005167 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005168 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005169
Chris Lattner318bf792007-03-18 22:51:34 +00005170
5171 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5172 if (Op1I) {
5173 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005174 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005175 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005176 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005177 I.swapOperands();
5178 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005179 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005180 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005181 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005182 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005183 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005184 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005185 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005186 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005187 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005188 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005189 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005190 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005191 std::swap(A, B);
5192 }
Chris Lattner318bf792007-03-18 22:51:34 +00005193 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005194 I.swapOperands(); // Simplified below.
5195 std::swap(Op0, Op1);
5196 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005197 }
Chris Lattner318bf792007-03-18 22:51:34 +00005198 }
5199
5200 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5201 if (Op0I) {
5202 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005203 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005204 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005205 if (A == Op1) // (B|A)^B == (A|B)^B
5206 std::swap(A, B);
5207 if (B == Op1) { // (A|B)^B == A & ~B
5208 Instruction *NotB =
Dan Gohman4ae51262009-08-12 16:23:25 +00005209 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005210 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005211 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005212 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005213 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005214 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005215 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005216 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005217 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005218 if (A == Op1) // (A&B)^A -> (B&A)^A
5219 std::swap(A, B);
5220 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005221 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005222 Instruction *N =
Dan Gohman4ae51262009-08-12 16:23:25 +00005223 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005224 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005225 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005226 }
Chris Lattner318bf792007-03-18 22:51:34 +00005227 }
5228
5229 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5230 if (Op0I && Op1I && Op0I->isShift() &&
5231 Op0I->getOpcode() == Op1I->getOpcode() &&
5232 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5233 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5234 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005235 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005236 Op1I->getOperand(0),
5237 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005238 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005239 Op1I->getOperand(1));
5240 }
5241
5242 if (Op0I && Op1I) {
5243 Value *A, *B, *C, *D;
5244 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005245 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5246 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005247 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005248 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005249 }
5250 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005251 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5252 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005253 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005254 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005255 }
5256
5257 // (A & B)^(C & D)
5258 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005259 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5260 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005261 // (X & Y)^(X & Y) -> (Y^Z) & X
5262 Value *X = 0, *Y = 0, *Z = 0;
5263 if (A == C)
5264 X = A, Y = B, Z = D;
5265 else if (A == D)
5266 X = A, Y = B, Z = C;
5267 else if (B == C)
5268 X = B, Y = A, Z = D;
5269 else if (B == D)
5270 X = B, Y = A, Z = C;
5271
5272 if (X) {
5273 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005274 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5275 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005276 }
5277 }
5278 }
5279
Reid Spencere4d87aa2006-12-23 06:05:41 +00005280 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5281 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005282 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005283 return R;
5284
Chris Lattner6fc205f2006-05-05 06:39:07 +00005285 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005286 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005287 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005288 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5289 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005290 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005291 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005292 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5293 I.getType(), TD) &&
5294 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5295 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005296 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005297 Op1C->getOperand(0),
5298 I.getName());
5299 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005300 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005301 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005302 }
Chris Lattner99c65742007-10-24 05:38:08 +00005303 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005304
Chris Lattner7e708292002-06-25 16:13:24 +00005305 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005306}
5307
Owen Andersond672ecb2009-07-03 00:17:18 +00005308static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005309 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005310 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005311}
Chris Lattnera96879a2004-09-29 17:40:11 +00005312
Dan Gohman6de29f82009-06-15 22:12:54 +00005313static bool HasAddOverflow(ConstantInt *Result,
5314 ConstantInt *In1, ConstantInt *In2,
5315 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005316 if (IsSigned)
5317 if (In2->getValue().isNegative())
5318 return Result->getValue().sgt(In1->getValue());
5319 else
5320 return Result->getValue().slt(In1->getValue());
5321 else
5322 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005323}
5324
Dan Gohman6de29f82009-06-15 22:12:54 +00005325/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005326/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005327static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005328 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005329 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005330 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005331
Dan Gohman6de29f82009-06-15 22:12:54 +00005332 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5333 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005334 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005335 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5336 ExtractElement(In1, Idx, Context),
5337 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005338 IsSigned))
5339 return true;
5340 }
5341 return false;
5342 }
5343
5344 return HasAddOverflow(cast<ConstantInt>(Result),
5345 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5346 IsSigned);
5347}
5348
5349static bool HasSubOverflow(ConstantInt *Result,
5350 ConstantInt *In1, ConstantInt *In2,
5351 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005352 if (IsSigned)
5353 if (In2->getValue().isNegative())
5354 return Result->getValue().slt(In1->getValue());
5355 else
5356 return Result->getValue().sgt(In1->getValue());
5357 else
5358 return Result->getValue().ugt(In1->getValue());
5359}
5360
Dan Gohman6de29f82009-06-15 22:12:54 +00005361/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5362/// overflowed for this type.
5363static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005364 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005365 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005366 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005367
5368 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5369 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005370 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005371 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5372 ExtractElement(In1, Idx, Context),
5373 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005374 IsSigned))
5375 return true;
5376 }
5377 return false;
5378 }
5379
5380 return HasSubOverflow(cast<ConstantInt>(Result),
5381 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5382 IsSigned);
5383}
5384
Chris Lattner574da9b2005-01-13 20:14:25 +00005385/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5386/// code necessary to compute the offset from the base pointer (without adding
5387/// in the base pointer). Return the result as a signed integer of intptr size.
5388static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005389 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005390 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson1d0be152009-08-13 21:58:54 +00005391 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Anderson07cf79e2009-07-06 23:00:19 +00005392 LLVMContext *Context = IC.getContext();
Owen Andersona7235ea2009-07-31 20:28:14 +00005393 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005394
5395 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005396 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005397 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005398
Gabor Greif177dd3f2008-06-12 21:37:33 +00005399 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5400 ++i, ++GTI) {
5401 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005402 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005403 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5404 if (OpC->isZero()) continue;
5405
5406 // Handle a struct index, which adds its field offset to the pointer.
5407 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5408 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5409
5410 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005411 Result =
Owen Andersoneed707b2009-07-24 23:12:02 +00005412 ConstantInt::get(*Context,
5413 RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005414 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005415 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005416 BinaryOperator::CreateAdd(Result,
Owen Andersoneed707b2009-07-24 23:12:02 +00005417 ConstantInt::get(IntPtrTy, Size),
Chris Lattnere62f0212007-04-28 04:52:43 +00005418 GEP->getName()+".offs"), I);
5419 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005420 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005421
Owen Andersoneed707b2009-07-24 23:12:02 +00005422 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005423 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005424 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5425 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005426 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005427 Result = ConstantExpr::getAdd(RC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005428 else {
5429 // Emit an add instruction.
5430 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005431 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005432 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005433 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005434 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005435 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005436 // Convert to correct type.
5437 if (Op->getType() != IntPtrTy) {
5438 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005439 Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005440 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005441 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5442 true,
5443 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005444 }
5445 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005446 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattnere62f0212007-04-28 04:52:43 +00005447 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005448 Op = ConstantExpr::getMul(OpC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005449 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005450 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005451 GEP->getName()+".idx"), I);
5452 }
5453
5454 // Emit an add instruction.
5455 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005456 Result = ConstantExpr::getAdd(cast<Constant>(Op),
Chris Lattnere62f0212007-04-28 04:52:43 +00005457 cast<Constant>(Result));
5458 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005459 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005460 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005461 }
5462 return Result;
5463}
5464
Chris Lattner10c0d912008-04-22 02:53:33 +00005465
Dan Gohman8f080f02009-07-17 22:16:21 +00005466/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5467/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5468/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5469/// be complex, and scales are involved. The above expression would also be
5470/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5471/// This later form is less amenable to optimization though, and we are allowed
5472/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005473///
5474/// If we can't emit an optimized form for this expression, this returns null.
5475///
5476static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5477 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005478 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005479 gep_type_iterator GTI = gep_type_begin(GEP);
5480
5481 // Check to see if this gep only has a single variable index. If so, and if
5482 // any constant indices are a multiple of its scale, then we can compute this
5483 // in terms of the scale of the variable index. For example, if the GEP
5484 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5485 // because the expression will cross zero at the same point.
5486 unsigned i, e = GEP->getNumOperands();
5487 int64_t Offset = 0;
5488 for (i = 1; i != e; ++i, ++GTI) {
5489 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5490 // Compute the aggregate offset of constant indices.
5491 if (CI->isZero()) continue;
5492
5493 // Handle a struct index, which adds its field offset to the pointer.
5494 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5495 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5496 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005497 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005498 Offset += Size*CI->getSExtValue();
5499 }
5500 } else {
5501 // Found our variable index.
5502 break;
5503 }
5504 }
5505
5506 // If there are no variable indices, we must have a constant offset, just
5507 // evaluate it the general way.
5508 if (i == e) return 0;
5509
5510 Value *VariableIdx = GEP->getOperand(i);
5511 // Determine the scale factor of the variable element. For example, this is
5512 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005513 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005514
5515 // Verify that there are no other variable indices. If so, emit the hard way.
5516 for (++i, ++GTI; i != e; ++i, ++GTI) {
5517 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5518 if (!CI) return 0;
5519
5520 // Compute the aggregate offset of constant indices.
5521 if (CI->isZero()) continue;
5522
5523 // Handle a struct index, which adds its field offset to the pointer.
5524 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5525 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5526 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005527 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005528 Offset += Size*CI->getSExtValue();
5529 }
5530 }
5531
5532 // Okay, we know we have a single variable index, which must be a
5533 // pointer/array/vector index. If there is no offset, life is simple, return
5534 // the index.
5535 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5536 if (Offset == 0) {
5537 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5538 // we don't need to bother extending: the extension won't affect where the
5539 // computation crosses zero.
5540 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson1d0be152009-08-13 21:58:54 +00005541 VariableIdx = new TruncInst(VariableIdx,
5542 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005543 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005544 return VariableIdx;
5545 }
5546
5547 // Otherwise, there is an index. The computation we will do will be modulo
5548 // the pointer size, so get it.
5549 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5550
5551 Offset &= PtrSizeMask;
5552 VariableScale &= PtrSizeMask;
5553
5554 // To do this transformation, any constant index must be a multiple of the
5555 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5556 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5557 // multiple of the variable scale.
5558 int64_t NewOffs = Offset / (int64_t)VariableScale;
5559 if (Offset != NewOffs*(int64_t)VariableScale)
5560 return 0;
5561
5562 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson1d0be152009-08-13 21:58:54 +00005563 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner10c0d912008-04-22 02:53:33 +00005564 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005565 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005566 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005567 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005568 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005569 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005570}
5571
5572
Reid Spencere4d87aa2006-12-23 06:05:41 +00005573/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005574/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005575Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005576 ICmpInst::Predicate Cond,
5577 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005578 // Look through bitcasts.
5579 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5580 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005581
Chris Lattner574da9b2005-01-13 20:14:25 +00005582 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005583 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005584 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005585 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005586 // know pointers can't overflow since the gep is inbounds. See if we can
5587 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005588 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5589
5590 // If not, synthesize the offset the hard way.
5591 if (Offset == 0)
5592 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005593 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005594 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005595 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005596 // If the base pointers are different, but the indices are the same, just
5597 // compare the base pointer.
5598 if (PtrBase != GEPRHS->getOperand(0)) {
5599 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005600 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005601 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005602 if (IndicesTheSame)
5603 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5604 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5605 IndicesTheSame = false;
5606 break;
5607 }
5608
5609 // If all indices are the same, just compare the base pointers.
5610 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005611 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005612 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005613
5614 // Otherwise, the base pointers are different and the indices are
5615 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005616 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005617 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005618
Chris Lattnere9d782b2005-01-13 22:25:21 +00005619 // If one of the GEPs has all zero indices, recurse.
5620 bool AllZeros = true;
5621 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5622 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5623 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5624 AllZeros = false;
5625 break;
5626 }
5627 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005628 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5629 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005630
5631 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005632 AllZeros = true;
5633 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5634 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5635 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5636 AllZeros = false;
5637 break;
5638 }
5639 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005640 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005641
Chris Lattner4401c9c2005-01-14 00:20:05 +00005642 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5643 // If the GEPs only differ by one index, compare it.
5644 unsigned NumDifferences = 0; // Keep track of # differences.
5645 unsigned DiffOperand = 0; // The operand that differs.
5646 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5647 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005648 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5649 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005650 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005651 NumDifferences = 2;
5652 break;
5653 } else {
5654 if (NumDifferences++) break;
5655 DiffOperand = i;
5656 }
5657 }
5658
5659 if (NumDifferences == 0) // SAME GEP?
5660 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005661 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005662 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005663
Chris Lattner4401c9c2005-01-14 00:20:05 +00005664 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005665 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5666 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005667 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005668 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005669 }
5670 }
5671
Reid Spencere4d87aa2006-12-23 06:05:41 +00005672 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005673 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005674 if (TD &&
5675 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005676 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5677 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5678 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5679 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005680 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005681 }
5682 }
5683 return 0;
5684}
5685
Chris Lattnera5406232008-05-19 20:18:56 +00005686/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5687///
5688Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5689 Instruction *LHSI,
5690 Constant *RHSC) {
5691 if (!isa<ConstantFP>(RHSC)) return 0;
5692 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5693
5694 // Get the width of the mantissa. We don't want to hack on conversions that
5695 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005696 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005697 if (MantissaWidth == -1) return 0; // Unknown.
5698
5699 // Check to see that the input is converted from an integer type that is small
5700 // enough that preserves all bits. TODO: check here for "known" sign bits.
5701 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
Dan Gohman6de29f82009-06-15 22:12:54 +00005702 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005703
5704 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005705 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5706 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005707 ++InputSize;
5708
5709 // If the conversion would lose info, don't hack on this.
5710 if ((int)InputSize > MantissaWidth)
5711 return 0;
5712
5713 // Otherwise, we can potentially simplify the comparison. We know that it
5714 // will always come through as an integer value and we know the constant is
5715 // not a NAN (it would have been previously simplified).
5716 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5717
5718 ICmpInst::Predicate Pred;
5719 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005720 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005721 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005722 case FCmpInst::FCMP_OEQ:
5723 Pred = ICmpInst::ICMP_EQ;
5724 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005725 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005726 case FCmpInst::FCMP_OGT:
5727 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5728 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005729 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005730 case FCmpInst::FCMP_OGE:
5731 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5732 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005733 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005734 case FCmpInst::FCMP_OLT:
5735 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5736 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005737 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005738 case FCmpInst::FCMP_OLE:
5739 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5740 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005741 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005742 case FCmpInst::FCMP_ONE:
5743 Pred = ICmpInst::ICMP_NE;
5744 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005745 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005746 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005747 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005748 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005749 }
5750
5751 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5752
5753 // Now we know that the APFloat is a normal number, zero or inf.
5754
Chris Lattner85162782008-05-20 03:50:52 +00005755 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005756 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005757 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005758
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005759 if (!LHSUnsigned) {
5760 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5761 // and large values.
5762 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5763 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5764 APFloat::rmNearestTiesToEven);
5765 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5766 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5767 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005768 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5769 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005770 }
5771 } else {
5772 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5773 // +INF and large values.
5774 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5775 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5776 APFloat::rmNearestTiesToEven);
5777 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5778 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5779 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005780 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5781 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005782 }
Chris Lattnera5406232008-05-19 20:18:56 +00005783 }
5784
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005785 if (!LHSUnsigned) {
5786 // See if the RHS value is < SignedMin.
5787 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5788 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5789 APFloat::rmNearestTiesToEven);
5790 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5791 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5792 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005793 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5794 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005795 }
Chris Lattnera5406232008-05-19 20:18:56 +00005796 }
5797
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005798 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5799 // [0, UMAX], but it may still be fractional. See if it is fractional by
5800 // casting the FP value to the integer value and back, checking for equality.
5801 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005802 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005803 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5804 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005805 if (!RHS.isZero()) {
5806 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005807 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5808 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005809 if (!Equal) {
5810 // If we had a comparison against a fractional value, we have to adjust
5811 // the compare predicate and sometimes the value. RHSC is rounded towards
5812 // zero at this point.
5813 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005814 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005815 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005816 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005817 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005818 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005819 case ICmpInst::ICMP_ULE:
5820 // (float)int <= 4.4 --> int <= 4
5821 // (float)int <= -4.4 --> false
5822 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005823 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005824 break;
5825 case ICmpInst::ICMP_SLE:
5826 // (float)int <= 4.4 --> int <= 4
5827 // (float)int <= -4.4 --> int < -4
5828 if (RHS.isNegative())
5829 Pred = ICmpInst::ICMP_SLT;
5830 break;
5831 case ICmpInst::ICMP_ULT:
5832 // (float)int < -4.4 --> false
5833 // (float)int < 4.4 --> int <= 4
5834 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005835 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005836 Pred = ICmpInst::ICMP_ULE;
5837 break;
5838 case ICmpInst::ICMP_SLT:
5839 // (float)int < -4.4 --> int < -4
5840 // (float)int < 4.4 --> int <= 4
5841 if (!RHS.isNegative())
5842 Pred = ICmpInst::ICMP_SLE;
5843 break;
5844 case ICmpInst::ICMP_UGT:
5845 // (float)int > 4.4 --> int > 4
5846 // (float)int > -4.4 --> true
5847 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005848 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005849 break;
5850 case ICmpInst::ICMP_SGT:
5851 // (float)int > 4.4 --> int > 4
5852 // (float)int > -4.4 --> int >= -4
5853 if (RHS.isNegative())
5854 Pred = ICmpInst::ICMP_SGE;
5855 break;
5856 case ICmpInst::ICMP_UGE:
5857 // (float)int >= -4.4 --> true
5858 // (float)int >= 4.4 --> int > 4
5859 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005860 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005861 Pred = ICmpInst::ICMP_UGT;
5862 break;
5863 case ICmpInst::ICMP_SGE:
5864 // (float)int >= -4.4 --> int >= -4
5865 // (float)int >= 4.4 --> int > 4
5866 if (!RHS.isNegative())
5867 Pred = ICmpInst::ICMP_SGT;
5868 break;
5869 }
Chris Lattnera5406232008-05-19 20:18:56 +00005870 }
5871 }
5872
5873 // Lower this FP comparison into an appropriate integer version of the
5874 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005875 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005876}
5877
Reid Spencere4d87aa2006-12-23 06:05:41 +00005878Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5879 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005880 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005881
Chris Lattner58e97462007-01-14 19:42:17 +00005882 // Fold trivial predicates.
5883 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005884 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005885 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005886 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005887
5888 // Simplify 'fcmp pred X, X'
5889 if (Op0 == Op1) {
5890 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005891 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005892 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5893 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5894 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Anderson5defacc2009-07-31 17:39:07 +00005895 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005896 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5897 case FCmpInst::FCMP_OLT: // True if ordered and less than
5898 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Anderson5defacc2009-07-31 17:39:07 +00005899 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005900
5901 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5902 case FCmpInst::FCMP_ULT: // True if unordered or less than
5903 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5904 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5905 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5906 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005907 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005908 return &I;
5909
5910 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5911 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5912 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5913 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5914 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5915 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005916 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005917 return &I;
5918 }
5919 }
5920
Reid Spencere4d87aa2006-12-23 06:05:41 +00005921 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Anderson1d0be152009-08-13 21:58:54 +00005922 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
Chris Lattnere87597f2004-10-16 18:11:37 +00005923
Reid Spencere4d87aa2006-12-23 06:05:41 +00005924 // Handle fcmp with constant RHS
5925 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005926 // If the constant is a nan, see if we can fold the comparison based on it.
5927 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5928 if (CFP->getValueAPF().isNaN()) {
5929 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005930 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005931 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5932 "Comparison must be either ordered or unordered!");
5933 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005934 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005935 }
5936 }
5937
Reid Spencere4d87aa2006-12-23 06:05:41 +00005938 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5939 switch (LHSI->getOpcode()) {
5940 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005941 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5942 // block. If in the same block, we're encouraging jump threading. If
5943 // not, we are just pessimizing the code by making an i1 phi.
5944 if (LHSI->getParent() == I.getParent())
5945 if (Instruction *NV = FoldOpIntoPhi(I))
5946 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005947 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005948 case Instruction::SIToFP:
5949 case Instruction::UIToFP:
5950 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5951 return NV;
5952 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005953 case Instruction::Select:
5954 // If either operand of the select is a constant, we can fold the
5955 // comparison into the select arms, which will cause one to be
5956 // constant folded and the select turned into a bitwise or.
5957 Value *Op1 = 0, *Op2 = 0;
5958 if (LHSI->hasOneUse()) {
5959 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5960 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005961 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005962 // Insert a new FCmp of the other select operand.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005963 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005964 LHSI->getOperand(2), RHSC,
5965 I.getName()), I);
5966 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5967 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005968 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005969 // Insert a new FCmp of the other select operand.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005970 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005971 LHSI->getOperand(1), RHSC,
5972 I.getName()), I);
5973 }
5974 }
5975
5976 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005977 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005978 break;
5979 }
5980 }
5981
5982 return Changed ? &I : 0;
5983}
5984
5985Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5986 bool Changed = SimplifyCompare(I);
5987 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5988 const Type *Ty = Op0->getType();
5989
5990 // icmp X, X
5991 if (Op0 == Op1)
Owen Anderson1d0be152009-08-13 21:58:54 +00005992 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005993 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005994
5995 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Anderson1d0be152009-08-13 21:58:54 +00005996 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005997
Reid Spencere4d87aa2006-12-23 06:05:41 +00005998 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005999 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00006000 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
6001 isa<ConstantPointerNull>(Op0)) &&
6002 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00006003 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00006004 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006005 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00006006
Reid Spencere4d87aa2006-12-23 06:05:41 +00006007 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00006008 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006009 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006010 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006011 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006012 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00006013 InsertNewInstBefore(Xor, I);
Dan Gohman4ae51262009-08-12 16:23:25 +00006014 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006015 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006016 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006017 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006018
Reid Spencere4d87aa2006-12-23 06:05:41 +00006019 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006020 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006021 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006022 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Dan Gohman4ae51262009-08-12 16:23:25 +00006023 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006024 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006025 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006026 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006027 case ICmpInst::ICMP_SGT:
6028 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006029 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006030 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Dan Gohman4ae51262009-08-12 16:23:25 +00006031 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006032 InsertNewInstBefore(Not, I);
6033 return BinaryOperator::CreateAnd(Not, Op0);
6034 }
6035 case ICmpInst::ICMP_UGE:
6036 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6037 // FALL THROUGH
6038 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Dan Gohman4ae51262009-08-12 16:23:25 +00006039 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006040 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006041 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006042 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006043 case ICmpInst::ICMP_SGE:
6044 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6045 // FALL THROUGH
6046 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Dan Gohman4ae51262009-08-12 16:23:25 +00006047 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006048 InsertNewInstBefore(Not, I);
6049 return BinaryOperator::CreateOr(Not, Op0);
6050 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006051 }
Chris Lattner8b170942002-08-09 23:47:40 +00006052 }
6053
Dan Gohman1c8491e2009-04-25 17:12:48 +00006054 unsigned BitWidth = 0;
6055 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006056 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6057 else if (Ty->isIntOrIntVector())
6058 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006059
6060 bool isSignBit = false;
6061
Dan Gohman81b28ce2008-09-16 18:46:06 +00006062 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006063 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006064 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006065
Chris Lattnerb6566012008-01-05 01:18:20 +00006066 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6067 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006068 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006069 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006070 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006071 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006072
Dan Gohman81b28ce2008-09-16 18:46:06 +00006073 // If we have an icmp le or icmp ge instruction, turn it into the
6074 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6075 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006076 switch (I.getPredicate()) {
6077 default: break;
6078 case ICmpInst::ICMP_ULE:
6079 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006080 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006081 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006082 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006083 case ICmpInst::ICMP_SLE:
6084 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006085 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006086 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006087 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006088 case ICmpInst::ICMP_UGE:
6089 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006090 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006091 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006092 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006093 case ICmpInst::ICMP_SGE:
6094 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006095 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006096 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006097 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006098 }
6099
Chris Lattner183661e2008-07-11 05:40:05 +00006100 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006101 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006102 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006103 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6104 }
6105
6106 // See if we can fold the comparison based on range information we can get
6107 // by checking whether bits are known to be zero or one in the input.
6108 if (BitWidth != 0) {
6109 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6110 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6111
6112 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006113 isSignBit ? APInt::getSignBit(BitWidth)
6114 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006115 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006116 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006117 if (SimplifyDemandedBits(I.getOperandUse(1),
6118 APInt::getAllOnesValue(BitWidth),
6119 Op1KnownZero, Op1KnownOne, 0))
6120 return &I;
6121
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006122 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006123 // in. Compute the Min, Max and RHS values based on the known bits. For the
6124 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006125 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6126 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6127 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6128 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6129 Op0Min, Op0Max);
6130 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6131 Op1Min, Op1Max);
6132 } else {
6133 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6134 Op0Min, Op0Max);
6135 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6136 Op1Min, Op1Max);
6137 }
6138
Chris Lattner183661e2008-07-11 05:40:05 +00006139 // If Min and Max are known to be the same, then SimplifyDemandedBits
6140 // figured out that the LHS is a constant. Just constant fold this now so
6141 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006142 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006143 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006144 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006145 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006146 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006147 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006148
Chris Lattner183661e2008-07-11 05:40:05 +00006149 // Based on the range information we know about the LHS, see if we can
6150 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006151 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006152 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006153 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006154 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006155 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006156 break;
6157 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006158 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006159 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006160 break;
6161 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006162 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006163 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006164 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006165 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006166 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006167 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006168 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6169 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006170 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006171 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006172
6173 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6174 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006175 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006176 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006177 }
Chris Lattner84dff672008-07-11 05:08:55 +00006178 break;
6179 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006180 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006181 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006182 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006183 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006184
6185 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006186 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006187 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6188 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006189 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006190 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006191
6192 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6193 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006194 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006195 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006196 }
Chris Lattner84dff672008-07-11 05:08:55 +00006197 break;
6198 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006199 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006200 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006201 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006202 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006203 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006204 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006205 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6206 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006207 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006208 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006209 }
Chris Lattner84dff672008-07-11 05:08:55 +00006210 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006211 case ICmpInst::ICMP_SGT:
6212 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006213 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006214 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006215 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006216
6217 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006218 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006219 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6220 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006221 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006222 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006223 }
6224 break;
6225 case ICmpInst::ICMP_SGE:
6226 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6227 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006228 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006229 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006230 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006231 break;
6232 case ICmpInst::ICMP_SLE:
6233 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6234 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006235 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006236 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006237 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006238 break;
6239 case ICmpInst::ICMP_UGE:
6240 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6241 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006242 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006243 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006244 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006245 break;
6246 case ICmpInst::ICMP_ULE:
6247 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6248 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006249 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006250 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006251 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006252 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006253 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006254
6255 // Turn a signed comparison into an unsigned one if both operands
6256 // are known to have the same sign.
6257 if (I.isSignedPredicate() &&
6258 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6259 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006260 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006261 }
6262
6263 // Test if the ICmpInst instruction is used exclusively by a select as
6264 // part of a minimum or maximum operation. If so, refrain from doing
6265 // any other folding. This helps out other analyses which understand
6266 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6267 // and CodeGen. And in this case, at least one of the comparison
6268 // operands has at least one user besides the compare (the select),
6269 // which would often largely negate the benefit of folding anyway.
6270 if (I.hasOneUse())
6271 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6272 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6273 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6274 return 0;
6275
6276 // See if we are doing a comparison between a constant and an instruction that
6277 // can be folded into the comparison.
6278 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006279 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006280 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006281 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006282 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006283 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6284 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006285 }
6286
Chris Lattner01deb9d2007-04-03 17:43:25 +00006287 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006288 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6289 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6290 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006291 case Instruction::GetElementPtr:
6292 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006293 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006294 bool isAllZeros = true;
6295 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6296 if (!isa<Constant>(LHSI->getOperand(i)) ||
6297 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6298 isAllZeros = false;
6299 break;
6300 }
6301 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006302 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006303 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006304 }
6305 break;
6306
Chris Lattner6970b662005-04-23 15:31:55 +00006307 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006308 // Only fold icmp into the PHI if the phi and fcmp are in the same
6309 // block. If in the same block, we're encouraging jump threading. If
6310 // not, we are just pessimizing the code by making an i1 phi.
6311 if (LHSI->getParent() == I.getParent())
6312 if (Instruction *NV = FoldOpIntoPhi(I))
6313 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006314 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006315 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006316 // If either operand of the select is a constant, we can fold the
6317 // comparison into the select arms, which will cause one to be
6318 // constant folded and the select turned into a bitwise or.
6319 Value *Op1 = 0, *Op2 = 0;
6320 if (LHSI->hasOneUse()) {
6321 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6322 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006323 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006324 // Insert a new ICmp of the other select operand.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006325 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006326 LHSI->getOperand(2), RHSC,
6327 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006328 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6329 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006330 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006331 // Insert a new ICmp of the other select operand.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006332 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006333 LHSI->getOperand(1), RHSC,
6334 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006335 }
6336 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006337
Chris Lattner6970b662005-04-23 15:31:55 +00006338 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006339 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006340 break;
6341 }
Chris Lattner4802d902007-04-06 18:57:34 +00006342 case Instruction::Malloc:
6343 // If we have (malloc != null), and if the malloc has a single use, we
6344 // can assume it is successful and remove the malloc.
6345 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6346 AddToWorkList(LHSI);
Owen Anderson1d0be152009-08-13 21:58:54 +00006347 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006348 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006349 }
6350 break;
6351 }
Chris Lattner6970b662005-04-23 15:31:55 +00006352 }
6353
Reid Spencere4d87aa2006-12-23 06:05:41 +00006354 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006355 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006356 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006357 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006358 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006359 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6360 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006361 return NI;
6362
Reid Spencere4d87aa2006-12-23 06:05:41 +00006363 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006364 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6365 // now.
6366 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6367 if (isa<PointerType>(Op0->getType()) &&
6368 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006369 // We keep moving the cast from the left operand over to the right
6370 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006371 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006372
Chris Lattner57d86372007-01-06 01:45:59 +00006373 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6374 // so eliminate it as well.
6375 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6376 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006377
Chris Lattnerde90b762003-11-03 04:25:02 +00006378 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006379 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006380 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006381 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006382 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006383 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006384 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006385 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006386 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006387 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006388 }
Chris Lattner57d86372007-01-06 01:45:59 +00006389 }
6390
6391 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006392 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006393 // This comes up when you have code like
6394 // int X = A < B;
6395 // if (X) ...
6396 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006397 // with a constant or another cast from the same type.
6398 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006399 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006400 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006401 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006402
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006403 // See if it's the same type of instruction on the left and right.
6404 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6405 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006406 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006407 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006408 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006409 default: break;
6410 case Instruction::Add:
6411 case Instruction::Sub:
6412 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006413 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006414 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006415 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006416 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6417 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6418 if (CI->getValue().isSignBit()) {
6419 ICmpInst::Predicate Pred = I.isSignedPredicate()
6420 ? I.getUnsignedPredicate()
6421 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006422 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006423 Op1I->getOperand(0));
6424 }
6425
6426 if (CI->getValue().isMaxSignedValue()) {
6427 ICmpInst::Predicate Pred = I.isSignedPredicate()
6428 ? I.getUnsignedPredicate()
6429 : I.getSignedPredicate();
6430 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006431 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006432 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006433 }
6434 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006435 break;
6436 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006437 if (!I.isEquality())
6438 break;
6439
Nick Lewycky5d52c452008-08-21 05:56:10 +00006440 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6441 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6442 // Mask = -1 >> count-trailing-zeros(Cst).
6443 if (!CI->isZero() && !CI->isOne()) {
6444 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006445 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006446 APInt::getLowBitsSet(AP.getBitWidth(),
6447 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006448 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006449 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6450 Mask);
6451 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6452 Mask);
6453 InsertNewInstBefore(And1, I);
6454 InsertNewInstBefore(And2, I);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006455 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006456 }
6457 }
6458 break;
6459 }
6460 }
6461 }
6462 }
6463
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006464 // ~x < ~y --> y < x
6465 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006466 if (match(Op0, m_Not(m_Value(A))) &&
6467 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006468 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006469 }
6470
Chris Lattner65b72ba2006-09-18 04:22:48 +00006471 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006472 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006473
6474 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006475 if (match(Op0, m_Neg(m_Value(A))) &&
6476 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006477 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006478
Dan Gohman4ae51262009-08-12 16:23:25 +00006479 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006480 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6481 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006482 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006483 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006484 }
6485
Dan Gohman4ae51262009-08-12 16:23:25 +00006486 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006487 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006488 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006489 if (match(B, m_ConstantInt(C1)) &&
6490 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006491 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006492 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattnercb504b92008-11-16 05:38:51 +00006493 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006494 return new ICmpInst(I.getPredicate(), A,
Chris Lattnercb504b92008-11-16 05:38:51 +00006495 InsertNewInstBefore(Xor, I));
6496 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006497
6498 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006499 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6500 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6501 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6502 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006503 }
6504 }
6505
Dan Gohman4ae51262009-08-12 16:23:25 +00006506 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006507 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006508 // A == (A^B) -> B == 0
6509 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006510 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006511 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006512 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006513
6514 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006515 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006516 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006517 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006518
6519 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006520 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006521 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006522 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006523
Chris Lattner9c2328e2006-11-14 06:06:06 +00006524 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6525 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006526 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6527 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006528 Value *X = 0, *Y = 0, *Z = 0;
6529
6530 if (A == C) {
6531 X = B; Y = D; Z = A;
6532 } else if (A == D) {
6533 X = B; Y = C; Z = A;
6534 } else if (B == C) {
6535 X = A; Y = D; Z = B;
6536 } else if (B == D) {
6537 X = A; Y = C; Z = B;
6538 }
6539
6540 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006541 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6542 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006543 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006544 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006545 return &I;
6546 }
6547 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006548 }
Chris Lattner7e708292002-06-25 16:13:24 +00006549 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006550}
6551
Chris Lattner562ef782007-06-20 23:46:26 +00006552
6553/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6554/// and CmpRHS are both known to be integer constants.
6555Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6556 ConstantInt *DivRHS) {
6557 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6558 const APInt &CmpRHSV = CmpRHS->getValue();
6559
6560 // FIXME: If the operand types don't match the type of the divide
6561 // then don't attempt this transform. The code below doesn't have the
6562 // logic to deal with a signed divide and an unsigned compare (and
6563 // vice versa). This is because (x /s C1) <s C2 produces different
6564 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6565 // (x /u C1) <u C2. Simply casting the operands and result won't
6566 // work. :( The if statement below tests that condition and bails
6567 // if it finds it.
6568 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6569 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6570 return 0;
6571 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006572 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006573 if (DivIsSigned && DivRHS->isAllOnesValue())
6574 return 0; // The overflow computation also screws up here
6575 if (DivRHS->isOne())
6576 return 0; // Not worth bothering, and eliminates some funny cases
6577 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006578
6579 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6580 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6581 // C2 (CI). By solving for X we can turn this into a range check
6582 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006583 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006584
6585 // Determine if the product overflows by seeing if the product is
6586 // not equal to the divide. Make sure we do the same kind of divide
6587 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006588 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6589 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006590
6591 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006592 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006593
Chris Lattner1dbfd482007-06-21 18:11:19 +00006594 // Figure out the interval that is being checked. For example, a comparison
6595 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6596 // Compute this interval based on the constants involved and the signedness of
6597 // the compare/divide. This computes a half-open interval, keeping track of
6598 // whether either value in the interval overflows. After analysis each
6599 // overflow variable is set to 0 if it's corresponding bound variable is valid
6600 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6601 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006602 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006603
Chris Lattner562ef782007-06-20 23:46:26 +00006604 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006605 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006606 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006607 HiOverflow = LoOverflow = ProdOV;
6608 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006609 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006610 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006611 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006612 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006613 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006614 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006615 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006616 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6617 HiOverflow = LoOverflow = ProdOV;
6618 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006619 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006620 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006621 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006622 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006623 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6624 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006625 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006626 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006627 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006628 true) ? -1 : 0;
6629 }
Chris Lattner562ef782007-06-20 23:46:26 +00006630 }
Dan Gohman76491272008-02-13 22:09:18 +00006631 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006632 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006633 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006634 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006635 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006636 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6637 HiOverflow = 1; // [INTMIN+1, overflow)
6638 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6639 }
Dan Gohman76491272008-02-13 22:09:18 +00006640 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006641 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006642 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006643 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006644 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006645 LoOverflow = AddWithOverflow(LoBound, HiBound,
6646 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006647 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006648 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6649 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006650 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006651 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006652 }
6653
Chris Lattner1dbfd482007-06-21 18:11:19 +00006654 // Dividing by a negative swaps the condition. LT <-> GT
6655 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006656 }
6657
6658 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006659 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006660 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006661 case ICmpInst::ICMP_EQ:
6662 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006663 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006664 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006665 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006666 ICmpInst::ICMP_UGE, X, LoBound);
6667 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006668 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006669 ICmpInst::ICMP_ULT, X, HiBound);
6670 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006671 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006672 case ICmpInst::ICMP_NE:
6673 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006674 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006675 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006676 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006677 ICmpInst::ICMP_ULT, X, LoBound);
6678 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006679 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006680 ICmpInst::ICMP_UGE, X, HiBound);
6681 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006682 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006683 case ICmpInst::ICMP_ULT:
6684 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006685 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006686 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006687 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006688 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006689 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006690 case ICmpInst::ICMP_UGT:
6691 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006692 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006693 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006694 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006695 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006696 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006697 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006698 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006699 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006700 }
6701}
6702
6703
Chris Lattner01deb9d2007-04-03 17:43:25 +00006704/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6705///
6706Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6707 Instruction *LHSI,
6708 ConstantInt *RHS) {
6709 const APInt &RHSV = RHS->getValue();
6710
6711 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006712 case Instruction::Trunc:
6713 if (ICI.isEquality() && LHSI->hasOneUse()) {
6714 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6715 // of the high bits truncated out of x are known.
6716 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6717 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6718 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6719 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6720 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6721
6722 // If all the high bits are known, we can do this xform.
6723 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6724 // Pull in the high bits from known-ones set.
6725 APInt NewRHS(RHS->getValue());
6726 NewRHS.zext(SrcBits);
6727 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006728 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006729 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006730 }
6731 }
6732 break;
6733
Duncan Sands0091bf22007-04-04 06:42:45 +00006734 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006735 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6736 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6737 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006738 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6739 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006740 Value *CompareVal = LHSI->getOperand(0);
6741
6742 // If the sign bit of the XorCST is not set, there is no change to
6743 // the operation, just stop using the Xor.
6744 if (!XorCST->getValue().isNegative()) {
6745 ICI.setOperand(0, CompareVal);
6746 AddToWorkList(LHSI);
6747 return &ICI;
6748 }
6749
6750 // Was the old condition true if the operand is positive?
6751 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6752
6753 // If so, the new one isn't.
6754 isTrueIfPositive ^= true;
6755
6756 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006757 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006758 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006759 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006760 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006761 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006762 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006763
6764 if (LHSI->hasOneUse()) {
6765 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6766 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6767 const APInt &SignBit = XorCST->getValue();
6768 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6769 ? ICI.getUnsignedPredicate()
6770 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006771 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006772 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006773 }
6774
6775 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006776 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006777 const APInt &NotSignBit = XorCST->getValue();
6778 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6779 ? ICI.getUnsignedPredicate()
6780 : ICI.getSignedPredicate();
6781 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006782 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006783 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006784 }
6785 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006786 }
6787 break;
6788 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6789 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6790 LHSI->getOperand(0)->hasOneUse()) {
6791 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6792
6793 // If the LHS is an AND of a truncating cast, we can widen the
6794 // and/compare to be the input width without changing the value
6795 // produced, eliminating a cast.
6796 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6797 // We can do this transformation if either the AND constant does not
6798 // have its sign bit set or if it is an equality comparison.
6799 // Extending a relational comparison when we're checking the sign
6800 // bit would not work.
6801 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006802 (ICI.isEquality() ||
6803 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006804 uint32_t BitWidth =
6805 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6806 APInt NewCST = AndCST->getValue();
6807 NewCST.zext(BitWidth);
6808 APInt NewCI = RHSV;
6809 NewCI.zext(BitWidth);
6810 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006811 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006812 ConstantInt::get(*Context, NewCST), LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006813 InsertNewInstBefore(NewAnd, ICI);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006814 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006815 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006816 }
6817 }
6818
6819 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6820 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6821 // happens a LOT in code produced by the C front-end, for bitfield
6822 // access.
6823 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6824 if (Shift && !Shift->isShift())
6825 Shift = 0;
6826
6827 ConstantInt *ShAmt;
6828 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6829 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6830 const Type *AndTy = AndCST->getType(); // Type of the and.
6831
6832 // We can fold this as long as we can't shift unknown bits
6833 // into the mask. This can only happen with signed shift
6834 // rights, as they sign-extend.
6835 if (ShAmt) {
6836 bool CanFold = Shift->isLogicalShift();
6837 if (!CanFold) {
6838 // To test for the bad case of the signed shr, see if any
6839 // of the bits shifted in could be tested after the mask.
6840 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6841 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6842
6843 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6844 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6845 AndCST->getValue()) == 0)
6846 CanFold = true;
6847 }
6848
6849 if (CanFold) {
6850 Constant *NewCst;
6851 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006852 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006853 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006854 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006855
6856 // Check to see if we are shifting out any of the bits being
6857 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006858 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006859 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006860 // If we shifted bits out, the fold is not going to work out.
6861 // As a special case, check to see if this means that the
6862 // result is always true or false now.
6863 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006864 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006865 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006866 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006867 } else {
6868 ICI.setOperand(1, NewCst);
6869 Constant *NewAndCST;
6870 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006871 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006872 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006873 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006874 LHSI->setOperand(1, NewAndCST);
6875 LHSI->setOperand(0, Shift->getOperand(0));
6876 AddToWorkList(Shift); // Shift is dead.
6877 AddUsesToWorkList(ICI);
6878 return &ICI;
6879 }
6880 }
6881 }
6882
6883 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6884 // preferable because it allows the C<<Y expression to be hoisted out
6885 // of a loop if Y is invariant and X is not.
6886 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006887 ICI.isEquality() && !Shift->isArithmeticShift() &&
6888 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006889 // Compute C << Y.
6890 Value *NS;
6891 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006892 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006893 Shift->getOperand(1), "tmp");
6894 } else {
6895 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006896 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006897 Shift->getOperand(1), "tmp");
6898 }
6899 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6900
6901 // Compute X & (C << Y).
6902 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006903 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006904 InsertNewInstBefore(NewAnd, ICI);
6905
6906 ICI.setOperand(0, NewAnd);
6907 return &ICI;
6908 }
6909 }
6910 break;
6911
Chris Lattnera0141b92007-07-15 20:42:37 +00006912 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6913 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6914 if (!ShAmt) break;
6915
6916 uint32_t TypeBits = RHSV.getBitWidth();
6917
6918 // Check that the shift amount is in range. If not, don't perform
6919 // undefined shifts. When the shift is visited it will be
6920 // simplified.
6921 if (ShAmt->uge(TypeBits))
6922 break;
6923
6924 if (ICI.isEquality()) {
6925 // If we are comparing against bits always shifted out, the
6926 // comparison cannot succeed.
6927 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006928 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006929 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006930 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6931 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006932 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006933 return ReplaceInstUsesWith(ICI, Cst);
6934 }
6935
6936 if (LHSI->hasOneUse()) {
6937 // Otherwise strength reduce the shift into an and.
6938 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6939 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006940 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006941 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006942
Chris Lattnera0141b92007-07-15 20:42:37 +00006943 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006944 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006945 Mask, LHSI->getName()+".mask");
6946 Value *And = InsertNewInstBefore(AndI, ICI);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006947 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006948 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006949 }
6950 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006951
6952 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6953 bool TrueIfSigned = false;
6954 if (LHSI->hasOneUse() &&
6955 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6956 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006957 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006958 (TypeBits-ShAmt->getZExtValue()-1));
6959 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006960 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006961 Mask, LHSI->getName()+".mask");
6962 Value *And = InsertNewInstBefore(AndI, ICI);
6963
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006964 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006965 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006966 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006967 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006968 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006969
6970 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006971 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006972 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006973 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006974 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006975
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006976 // Check that the shift amount is in range. If not, don't perform
6977 // undefined shifts. When the shift is visited it will be
6978 // simplified.
6979 uint32_t TypeBits = RHSV.getBitWidth();
6980 if (ShAmt->uge(TypeBits))
6981 break;
6982
6983 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006984
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006985 // If we are comparing against bits always shifted out, the
6986 // comparison cannot succeed.
6987 APInt Comp = RHSV << ShAmtVal;
6988 if (LHSI->getOpcode() == Instruction::LShr)
6989 Comp = Comp.lshr(ShAmtVal);
6990 else
6991 Comp = Comp.ashr(ShAmtVal);
6992
6993 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6994 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006995 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006996 return ReplaceInstUsesWith(ICI, Cst);
6997 }
6998
6999 // Otherwise, check to see if the bits shifted out are known to be zero.
7000 // If so, we can compare against the unshifted value:
7001 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007002 if (LHSI->hasOneUse() &&
7003 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007004 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007005 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007006 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007007 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007008
Evan Chengf30752c2008-04-23 00:38:06 +00007009 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007010 // Otherwise strength reduce the shift into an and.
7011 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007012 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007013
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007014 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007015 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007016 Mask, LHSI->getName()+".mask");
7017 Value *And = InsertNewInstBefore(AndI, ICI);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007018 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007019 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007020 }
7021 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007022 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007023
7024 case Instruction::SDiv:
7025 case Instruction::UDiv:
7026 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7027 // Fold this div into the comparison, producing a range check.
7028 // Determine, based on the divide type, what the range is being
7029 // checked. If there is an overflow on the low or high side, remember
7030 // it, otherwise compute the range [low, hi) bounding the new value.
7031 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007032 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7033 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7034 DivRHS))
7035 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007036 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007037
7038 case Instruction::Add:
7039 // Fold: icmp pred (add, X, C1), C2
7040
7041 if (!ICI.isEquality()) {
7042 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7043 if (!LHSC) break;
7044 const APInt &LHSV = LHSC->getValue();
7045
7046 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7047 .subtract(LHSV);
7048
7049 if (ICI.isSignedPredicate()) {
7050 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007051 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007052 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007053 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007054 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007055 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007056 }
7057 } else {
7058 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007059 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007060 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007061 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007062 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007063 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007064 }
7065 }
7066 }
7067 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007068 }
7069
7070 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7071 if (ICI.isEquality()) {
7072 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7073
7074 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7075 // the second operand is a constant, simplify a bit.
7076 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7077 switch (BO->getOpcode()) {
7078 case Instruction::SRem:
7079 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7080 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7081 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7082 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7083 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007084 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007085 BO->getName());
7086 InsertNewInstBefore(NewRem, ICI);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007087 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007088 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007089 }
7090 }
7091 break;
7092 case Instruction::Add:
7093 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7094 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7095 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007096 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007097 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007098 } else if (RHSV == 0) {
7099 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7100 // efficiently invertible, or if the add has just this one use.
7101 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7102
Dan Gohman186a6362009-08-12 16:04:34 +00007103 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007104 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007105 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007106 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007107 else if (BO->hasOneUse()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00007108 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007109 InsertNewInstBefore(Neg, ICI);
7110 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007111 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007112 }
7113 }
7114 break;
7115 case Instruction::Xor:
7116 // For the xor case, we can xor two constants together, eliminating
7117 // the explicit xor.
7118 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007119 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007120 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007121
7122 // FALLTHROUGH
7123 case Instruction::Sub:
7124 // Replace (([sub|xor] A, B) != 0) with (A != B)
7125 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007126 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007127 BO->getOperand(1));
7128 break;
7129
7130 case Instruction::Or:
7131 // If bits are being or'd in that are not present in the constant we
7132 // are comparing against, then the comparison could never succeed!
7133 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007134 Constant *NotCI = ConstantExpr::getNot(RHS);
7135 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007136 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007137 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007138 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007139 }
7140 break;
7141
7142 case Instruction::And:
7143 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7144 // If bits are being compared against that are and'd out, then the
7145 // comparison can never succeed!
7146 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007147 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007148 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007149 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007150
7151 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7152 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007153 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007154 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007155 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007156
7157 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007158 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007159 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007160 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007161 ICmpInst::Predicate pred = isICMP_NE ?
7162 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007163 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007164 }
7165
7166 // ((X & ~7) == 0) --> X < 8
7167 if (RHSV == 0 && isHighOnes(BOC)) {
7168 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007169 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007170 ICmpInst::Predicate pred = isICMP_NE ?
7171 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007172 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007173 }
7174 }
7175 default: break;
7176 }
7177 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7178 // Handle icmp {eq|ne} <intrinsic>, intcst.
7179 if (II->getIntrinsicID() == Intrinsic::bswap) {
7180 AddToWorkList(II);
7181 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007182 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007183 return &ICI;
7184 }
7185 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007186 }
7187 return 0;
7188}
7189
7190/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7191/// We only handle extending casts so far.
7192///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007193Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7194 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007195 Value *LHSCIOp = LHSCI->getOperand(0);
7196 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007197 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007198 Value *RHSCIOp;
7199
Chris Lattner8c756c12007-05-05 22:41:33 +00007200 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7201 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007202 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7203 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007204 cast<IntegerType>(DestTy)->getBitWidth()) {
7205 Value *RHSOp = 0;
7206 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007207 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007208 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7209 RHSOp = RHSC->getOperand(0);
7210 // If the pointer types don't match, insert a bitcast.
7211 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007212 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007213 }
7214
7215 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007216 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007217 }
7218
7219 // The code below only handles extension cast instructions, so far.
7220 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007221 if (LHSCI->getOpcode() != Instruction::ZExt &&
7222 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007223 return 0;
7224
Reid Spencere4d87aa2006-12-23 06:05:41 +00007225 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7226 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007227
Reid Spencere4d87aa2006-12-23 06:05:41 +00007228 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007229 // Not an extension from the same type?
7230 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007231 if (RHSCIOp->getType() != LHSCIOp->getType())
7232 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007233
Nick Lewycky4189a532008-01-28 03:48:02 +00007234 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007235 // and the other is a zext), then we can't handle this.
7236 if (CI->getOpcode() != LHSCI->getOpcode())
7237 return 0;
7238
Nick Lewycky4189a532008-01-28 03:48:02 +00007239 // Deal with equality cases early.
7240 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007241 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007242
7243 // A signed comparison of sign extended values simplifies into a
7244 // signed comparison.
7245 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007246 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007247
7248 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007249 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007250 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007251
Reid Spencere4d87aa2006-12-23 06:05:41 +00007252 // If we aren't dealing with a constant on the RHS, exit early
7253 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7254 if (!CI)
7255 return 0;
7256
7257 // Compute the constant that would happen if we truncated to SrcTy then
7258 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007259 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7260 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007261 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007262
7263 // If the re-extended constant didn't change...
7264 if (Res2 == CI) {
7265 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7266 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007267 // %A = sext i16 %X to i32
7268 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007269 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007270 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007271 // because %A may have negative value.
7272 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007273 // However, we allow this when the compare is EQ/NE, because they are
7274 // signless.
7275 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007276 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007277 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007278 }
7279
7280 // The re-extended constant changed so the constant cannot be represented
7281 // in the shorter type. Consequently, we cannot emit a simple comparison.
7282
7283 // First, handle some easy cases. We know the result cannot be equal at this
7284 // point so handle the ICI.isEquality() cases
7285 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007286 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007287 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007288 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007289
7290 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7291 // should have been folded away previously and not enter in here.
7292 Value *Result;
7293 if (isSignedCmp) {
7294 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007295 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007296 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007297 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007298 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007299 } else {
7300 // We're performing an unsigned comparison.
7301 if (isSignedExt) {
7302 // We're performing an unsigned comp with a sign extended value.
7303 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007304 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007305 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT,
Owen Anderson333c4002009-07-09 23:48:35 +00007306 LHSCIOp, NegOne, ICI.getName()), ICI);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007307 } else {
7308 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007309 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007310 }
7311 }
7312
7313 // Finally, return the value computed.
7314 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007315 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007316 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007317
7318 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7319 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7320 "ICmp should be folded!");
7321 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007322 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007323 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007324}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007325
Reid Spencer832254e2007-02-02 02:16:23 +00007326Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7327 return commonShiftTransforms(I);
7328}
7329
7330Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7331 return commonShiftTransforms(I);
7332}
7333
7334Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007335 if (Instruction *R = commonShiftTransforms(I))
7336 return R;
7337
7338 Value *Op0 = I.getOperand(0);
7339
7340 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7341 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7342 if (CSI->isAllOnesValue())
7343 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007344
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007345 // See if we can turn a signed shr into an unsigned shr.
7346 if (MaskedValueIsZero(Op0,
7347 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7348 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7349
7350 // Arithmetic shifting an all-sign-bit value is a no-op.
7351 unsigned NumSignBits = ComputeNumSignBits(Op0);
7352 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7353 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007354
Chris Lattner348f6652007-12-06 01:59:46 +00007355 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007356}
7357
7358Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7359 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007360 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007361
7362 // shl X, 0 == X and shr X, 0 == X
7363 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007364 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7365 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007366 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007367
Reid Spencere4d87aa2006-12-23 06:05:41 +00007368 if (isa<UndefValue>(Op0)) {
7369 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007370 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007371 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007372 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007373 }
7374 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007375 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7376 return ReplaceInstUsesWith(I, Op0);
7377 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007378 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007379 }
7380
Dan Gohman9004c8a2009-05-21 02:28:33 +00007381 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007382 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007383 return &I;
7384
Chris Lattner2eefe512004-04-09 19:05:30 +00007385 // Try to fold constant and into select arguments.
7386 if (isa<Constant>(Op0))
7387 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007388 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007389 return R;
7390
Reid Spencerb83eb642006-10-20 07:07:24 +00007391 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007392 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7393 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007394 return 0;
7395}
7396
Reid Spencerb83eb642006-10-20 07:07:24 +00007397Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007398 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007399 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007400
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007401 // See if we can simplify any instructions used by the instruction whose sole
7402 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007403 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007404
Dan Gohmana119de82009-06-14 23:30:43 +00007405 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7406 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007407 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007408 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007409 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007410 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007411 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007412 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007413 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007414 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007415 }
7416
7417 // ((X*C1) << C2) == (X * (C1 << C2))
7418 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7419 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7420 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007421 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007422 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007423
7424 // Try to fold constant and into select arguments.
7425 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7426 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7427 return R;
7428 if (isa<PHINode>(Op0))
7429 if (Instruction *NV = FoldOpIntoPhi(I))
7430 return NV;
7431
Chris Lattner8999dd32007-12-22 09:07:47 +00007432 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7433 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7434 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7435 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7436 // place. Don't try to do this transformation in this case. Also, we
7437 // require that the input operand is a shift-by-constant so that we have
7438 // confidence that the shifts will get folded together. We could do this
7439 // xform in more cases, but it is unlikely to be profitable.
7440 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7441 isa<ConstantInt>(TrOp->getOperand(1))) {
7442 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007443 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007444 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007445 I.getName());
7446 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7447
7448 // For logical shifts, the truncation has the effect of making the high
7449 // part of the register be zeros. Emulate this by inserting an AND to
7450 // clear the top bits as needed. This 'and' will usually be zapped by
7451 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007452 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7453 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007454 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7455
7456 // The mask we constructed says what the trunc would do if occurring
7457 // between the shifts. We want to know the effect *after* the second
7458 // shift. We know that it is a logical shift by a constant, so adjust the
7459 // mask as appropriate.
7460 if (I.getOpcode() == Instruction::Shl)
7461 MaskV <<= Op1->getZExtValue();
7462 else {
7463 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7464 MaskV = MaskV.lshr(Op1->getZExtValue());
7465 }
7466
Owen Andersond672ecb2009-07-03 00:17:18 +00007467 Instruction *And =
Owen Andersoneed707b2009-07-24 23:12:02 +00007468 BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
Owen Andersond672ecb2009-07-03 00:17:18 +00007469 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007470 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7471
7472 // Return the value truncated to the interesting size.
7473 return new TruncInst(And, I.getType());
7474 }
7475 }
7476
Chris Lattner4d5542c2006-01-06 07:12:35 +00007477 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007478 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7479 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7480 Value *V1, *V2;
7481 ConstantInt *CC;
7482 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007483 default: break;
7484 case Instruction::Add:
7485 case Instruction::And:
7486 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007487 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007488 // These operators commute.
7489 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007490 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007491 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007492 m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007493 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007494 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007495 Op0BO->getName());
7496 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007497 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007498 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007499 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007500 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007501 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007502 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007503 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007504 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007505
Chris Lattner150f12a2005-09-18 06:30:59 +00007506 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007507 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007508 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007509 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007510 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007511 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007512 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007513 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007514 Op0BO->getOperand(0), Op1,
7515 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007516 InsertNewInstBefore(YS, I); // (Y << C)
7517 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007518 BinaryOperator::CreateAnd(V1,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007519 ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007520 V1->getName()+".mask");
7521 InsertNewInstBefore(XM, I); // X & (CC << C)
7522
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007523 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007524 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007525 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007526
Reid Spencera07cb7d2007-02-02 14:41:37 +00007527 // FALL THROUGH.
7528 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007529 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007530 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007531 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007532 m_Specific(Op1)))) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007533 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007534 Op0BO->getOperand(1), Op1,
7535 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007536 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007537 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007538 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007539 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007540 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007541 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007542 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007543 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007544 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007545
Chris Lattner13d4ab42006-05-31 21:14:00 +00007546 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007547 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7548 match(Op0BO->getOperand(0),
7549 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007550 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007551 cast<BinaryOperator>(Op0BO->getOperand(0))
7552 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007553 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007554 Op0BO->getOperand(1), Op1,
7555 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007556 InsertNewInstBefore(YS, I); // (Y << C)
7557 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007558 BinaryOperator::CreateAnd(V1,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007559 ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007560 V1->getName()+".mask");
7561 InsertNewInstBefore(XM, I); // X & (CC << C)
7562
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007563 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007564 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007565
Chris Lattner11021cb2005-09-18 05:12:10 +00007566 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007567 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007568 }
7569
7570
7571 // If the operand is an bitwise operator with a constant RHS, and the
7572 // shift is the only use, we can pull it out of the shift.
7573 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7574 bool isValid = true; // Valid only for And, Or, Xor
7575 bool highBitSet = false; // Transform if high bit of constant set?
7576
7577 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007578 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007579 case Instruction::Add:
7580 isValid = isLeftShift;
7581 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007582 case Instruction::Or:
7583 case Instruction::Xor:
7584 highBitSet = false;
7585 break;
7586 case Instruction::And:
7587 highBitSet = true;
7588 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007589 }
7590
7591 // If this is a signed shift right, and the high bit is modified
7592 // by the logical operation, do not perform the transformation.
7593 // The highBitSet boolean indicates the value of the high bit of
7594 // the constant which would cause it to be modified for this
7595 // operation.
7596 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007597 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007598 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007599
7600 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007601 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007602
7603 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007604 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007605 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007606 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007607
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007608 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007609 NewRHS);
7610 }
7611 }
7612 }
7613 }
7614
Chris Lattnerad0124c2006-01-06 07:52:12 +00007615 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007616 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7617 if (ShiftOp && !ShiftOp->isShift())
7618 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007619
Reid Spencerb83eb642006-10-20 07:07:24 +00007620 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007621 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007622 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7623 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007624 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7625 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7626 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007627
Zhou Sheng4351c642007-04-02 08:20:41 +00007628 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007629
7630 const IntegerType *Ty = cast<IntegerType>(I.getType());
7631
7632 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007633 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007634 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7635 // saturates.
7636 if (AmtSum >= TypeBits) {
7637 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007638 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007639 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7640 }
7641
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007642 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007643 ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007644 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7645 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007646 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007647 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007648
Chris Lattnerb87056f2007-02-05 00:57:54 +00007649 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007650 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007651 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7652 I.getOpcode() == Instruction::LShr) {
7653 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007654 if (AmtSum >= TypeBits)
7655 AmtSum = TypeBits-1;
7656
Chris Lattnerb87056f2007-02-05 00:57:54 +00007657 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007658 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007659 InsertNewInstBefore(Shift, I);
7660
Zhou Shenge9e03f62007-03-28 15:02:20 +00007661 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007662 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007663 }
7664
Chris Lattnerb87056f2007-02-05 00:57:54 +00007665 // Okay, if we get here, one shift must be left, and the other shift must be
7666 // right. See if the amounts are equal.
7667 if (ShiftAmt1 == ShiftAmt2) {
7668 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7669 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007670 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007671 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007672 }
7673 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7674 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007675 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007676 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007677 }
7678 // We can simplify ((X << C) >>s C) into a trunc + sext.
7679 // NOTE: we could do this for any C, but that would make 'unusual' integer
7680 // types. For now, just stick to ones well-supported by the code
7681 // generators.
7682 const Type *SExtType = 0;
7683 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007684 case 1 :
7685 case 8 :
7686 case 16 :
7687 case 32 :
7688 case 64 :
7689 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007690 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007691 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007692 default: break;
7693 }
7694 if (SExtType) {
7695 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7696 InsertNewInstBefore(NewTrunc, I);
7697 return new SExtInst(NewTrunc, Ty);
7698 }
7699 // Otherwise, we can't handle it yet.
7700 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007701 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007702
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007703 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007704 if (I.getOpcode() == Instruction::Shl) {
7705 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7706 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007707 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007708 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007709 InsertNewInstBefore(Shift, I);
7710
Reid Spencer55702aa2007-03-25 21:11:44 +00007711 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007712 return BinaryOperator::CreateAnd(Shift,
7713 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007714 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007715
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007716 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007717 if (I.getOpcode() == Instruction::LShr) {
7718 assert(ShiftOp->getOpcode() == Instruction::Shl);
7719 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007720 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007721 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007722
Reid Spencerd5e30f02007-03-26 17:18:58 +00007723 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007724 return BinaryOperator::CreateAnd(Shift,
7725 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007726 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007727
7728 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7729 } else {
7730 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007731 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007732
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007733 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007734 if (I.getOpcode() == Instruction::Shl) {
7735 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7736 ShiftOp->getOpcode() == Instruction::AShr);
7737 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007738 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007739 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007740 InsertNewInstBefore(Shift, I);
7741
Reid Spencer55702aa2007-03-25 21:11:44 +00007742 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007743 return BinaryOperator::CreateAnd(Shift,
7744 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007745 }
7746
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007747 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007748 if (I.getOpcode() == Instruction::LShr) {
7749 assert(ShiftOp->getOpcode() == Instruction::Shl);
7750 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007751 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007752 InsertNewInstBefore(Shift, I);
7753
Reid Spencer68d27cf2007-03-26 23:45:51 +00007754 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007755 return BinaryOperator::CreateAnd(Shift,
7756 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007757 }
7758
7759 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007760 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007761 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007762 return 0;
7763}
7764
Chris Lattnera1be5662002-05-02 17:06:02 +00007765
Chris Lattnercfd65102005-10-29 04:36:15 +00007766/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7767/// expression. If so, decompose it, returning some value X, such that Val is
7768/// X*Scale+Offset.
7769///
7770static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007771 int &Offset, LLVMContext *Context) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007772 assert(Val->getType() == Type::getInt32Ty(*Context) && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007773 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007774 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007775 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007776 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007777 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7778 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7779 if (I->getOpcode() == Instruction::Shl) {
7780 // This is a value scaled by '1 << the shift amt'.
7781 Scale = 1U << RHS->getZExtValue();
7782 Offset = 0;
7783 return I->getOperand(0);
7784 } else if (I->getOpcode() == Instruction::Mul) {
7785 // This value is scaled by 'RHS'.
7786 Scale = RHS->getZExtValue();
7787 Offset = 0;
7788 return I->getOperand(0);
7789 } else if (I->getOpcode() == Instruction::Add) {
7790 // We have X+C. Check to see if we really have (X*C2)+C1,
7791 // where C1 is divisible by C2.
7792 unsigned SubScale;
7793 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007794 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7795 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007796 Offset += RHS->getZExtValue();
7797 Scale = SubScale;
7798 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007799 }
7800 }
7801 }
7802
7803 // Otherwise, we can't look past this.
7804 Scale = 1;
7805 Offset = 0;
7806 return Val;
7807}
7808
7809
Chris Lattnerb3f83972005-10-24 06:03:58 +00007810/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7811/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007812Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007813 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007814 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007815
Chris Lattnerb53c2382005-10-24 06:22:12 +00007816 // Remove any uses of AI that are dead.
7817 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007818
Chris Lattnerb53c2382005-10-24 06:22:12 +00007819 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7820 Instruction *User = cast<Instruction>(*UI++);
7821 if (isInstructionTriviallyDead(User)) {
7822 while (UI != E && *UI == User)
7823 ++UI; // If this instruction uses AI more than once, don't break UI.
7824
Chris Lattnerb53c2382005-10-24 06:22:12 +00007825 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007826 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007827 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007828 }
7829 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007830
7831 // This requires TargetData to get the alloca alignment and size information.
7832 if (!TD) return 0;
7833
Chris Lattnerb3f83972005-10-24 06:03:58 +00007834 // Get the type really allocated and the type casted to.
7835 const Type *AllocElTy = AI.getAllocatedType();
7836 const Type *CastElTy = PTy->getElementType();
7837 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007838
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007839 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7840 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007841 if (CastElTyAlign < AllocElTyAlign) return 0;
7842
Chris Lattner39387a52005-10-24 06:35:18 +00007843 // If the allocation has multiple uses, only promote it if we are strictly
7844 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007845 // same, we open the door to infinite loops of various kinds. (A reference
7846 // from a dbg.declare doesn't count as a use for this purpose.)
7847 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7848 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007849
Duncan Sands777d2302009-05-09 07:06:46 +00007850 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7851 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007852 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007853
Chris Lattner455fcc82005-10-29 03:19:53 +00007854 // See if we can satisfy the modulus by pulling a scale out of the array
7855 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007856 unsigned ArraySizeScale;
7857 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007858 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007859 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7860 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007861
Chris Lattner455fcc82005-10-29 03:19:53 +00007862 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7863 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007864 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7865 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007866
Chris Lattner455fcc82005-10-29 03:19:53 +00007867 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7868 Value *Amt = 0;
7869 if (Scale == 1) {
7870 Amt = NumElements;
7871 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007872 // If the allocation size is constant, form a constant mul expression
Owen Anderson1d0be152009-08-13 21:58:54 +00007873 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Reid Spencerc5b206b2006-12-31 05:48:39 +00007874 if (isa<ConstantInt>(NumElements))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007875 Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
Dan Gohman6de29f82009-06-15 22:12:54 +00007876 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007877 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007878 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007879 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007880 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007881 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007882 }
7883
Jeff Cohen86796be2007-04-04 16:58:57 +00007884 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007885 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007886 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007887 Amt = InsertNewInstBefore(Tmp, AI);
7888 }
7889
Chris Lattnerb3f83972005-10-24 06:03:58 +00007890 AllocationInst *New;
7891 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +00007892 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007893 else
Owen Anderson50dead02009-07-15 23:53:25 +00007894 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007895 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007896 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007897
Dale Johannesena0a66372009-03-05 00:39:02 +00007898 // If the allocation has one real use plus a dbg.declare, just remove the
7899 // declare.
7900 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7901 EraseInstFromFunction(*DI);
7902 }
7903 // If the allocation has multiple real uses, insert a cast and change all
7904 // things that used it to use the new cast. This will also hack on CI, but it
7905 // will die soon.
7906 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007907 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007908 // New is the allocation instruction, pointer typed. AI is the original
7909 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7910 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007911 InsertNewInstBefore(NewCast, AI);
7912 AI.replaceAllUsesWith(NewCast);
7913 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007914 return ReplaceInstUsesWith(CI, New);
7915}
7916
Chris Lattner70074e02006-05-13 02:06:03 +00007917/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007918/// and return it as type Ty without inserting any new casts and without
7919/// changing the computed value. This is used by code that tries to decide
7920/// whether promoting or shrinking integer operations to wider or smaller types
7921/// will allow us to eliminate a truncate or extend.
7922///
7923/// This is a truncation operation if Ty is smaller than V->getType(), or an
7924/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007925///
7926/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7927/// should return true if trunc(V) can be computed by computing V in the smaller
7928/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7929/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7930/// efficiently truncated.
7931///
7932/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7933/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7934/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007935bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007936 unsigned CastOpc,
7937 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007938 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007939 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007940 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007941
7942 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007943 if (!I) return false;
7944
Dan Gohman6de29f82009-06-15 22:12:54 +00007945 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007946
Chris Lattner951626b2007-08-02 06:11:14 +00007947 // If this is an extension or truncate, we can often eliminate it.
7948 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7949 // If this is a cast from the destination type, we can trivially eliminate
7950 // it, and this will remove a cast overall.
7951 if (I->getOperand(0)->getType() == Ty) {
7952 // If the first operand is itself a cast, and is eliminable, do not count
7953 // this as an eliminable cast. We would prefer to eliminate those two
7954 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007955 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007956 ++NumCastsRemoved;
7957 return true;
7958 }
7959 }
7960
7961 // We can't extend or shrink something that has multiple uses: doing so would
7962 // require duplicating the instruction in general, which isn't profitable.
7963 if (!I->hasOneUse()) return false;
7964
Evan Chengf35fd542009-01-15 17:01:23 +00007965 unsigned Opc = I->getOpcode();
7966 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007967 case Instruction::Add:
7968 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007969 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007970 case Instruction::And:
7971 case Instruction::Or:
7972 case Instruction::Xor:
7973 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007974 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007975 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007976 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007977 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007978
Eli Friedman070a9812009-07-13 22:46:01 +00007979 case Instruction::UDiv:
7980 case Instruction::URem: {
7981 // UDiv and URem can be truncated if all the truncated bits are zero.
7982 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7983 uint32_t BitWidth = Ty->getScalarSizeInBits();
7984 if (BitWidth < OrigBitWidth) {
7985 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7986 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7987 MaskedValueIsZero(I->getOperand(1), Mask)) {
7988 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7989 NumCastsRemoved) &&
7990 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7991 NumCastsRemoved);
7992 }
7993 }
7994 break;
7995 }
Chris Lattner46b96052006-11-29 07:18:39 +00007996 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007997 // If we are truncating the result of this SHL, and if it's a shift of a
7998 // constant amount, we can always perform a SHL in a smaller type.
7999 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008000 uint32_t BitWidth = Ty->getScalarSizeInBits();
8001 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00008002 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00008003 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008004 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008005 }
8006 break;
8007 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008008 // If this is a truncate of a logical shr, we can truncate it to a smaller
8009 // lshr iff we know that the bits we would otherwise be shifting in are
8010 // already zeros.
8011 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008012 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8013 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008014 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008015 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008016 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8017 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008018 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008019 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008020 }
8021 }
Chris Lattner46b96052006-11-29 07:18:39 +00008022 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008023 case Instruction::ZExt:
8024 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008025 case Instruction::Trunc:
8026 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008027 // can safely replace it. Note that replacing it does not reduce the number
8028 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008029 if (Opc == CastOpc)
8030 return true;
8031
8032 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008033 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008034 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008035 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008036 case Instruction::Select: {
8037 SelectInst *SI = cast<SelectInst>(I);
8038 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008039 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008040 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008041 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008042 }
Chris Lattner8114b712008-06-18 04:00:49 +00008043 case Instruction::PHI: {
8044 // We can change a phi if we can change all operands.
8045 PHINode *PN = cast<PHINode>(I);
8046 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8047 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008048 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008049 return false;
8050 return true;
8051 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008052 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008053 // TODO: Can handle more cases here.
8054 break;
8055 }
8056
8057 return false;
8058}
8059
8060/// EvaluateInDifferentType - Given an expression that
8061/// CanEvaluateInDifferentType returns true for, actually insert the code to
8062/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008063Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008064 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008065 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00008066 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00008067 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008068
8069 // Otherwise, it must be an instruction.
8070 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008071 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008072 unsigned Opc = I->getOpcode();
8073 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008074 case Instruction::Add:
8075 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008076 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008077 case Instruction::And:
8078 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008079 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008080 case Instruction::AShr:
8081 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008082 case Instruction::Shl:
8083 case Instruction::UDiv:
8084 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008085 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008086 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008087 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008088 break;
8089 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008090 case Instruction::Trunc:
8091 case Instruction::ZExt:
8092 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008093 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008094 // just return the source. There's no need to insert it because it is not
8095 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008096 if (I->getOperand(0)->getType() == Ty)
8097 return I->getOperand(0);
8098
Chris Lattner8114b712008-06-18 04:00:49 +00008099 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008100 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008101 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008102 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008103 case Instruction::Select: {
8104 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8105 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8106 Res = SelectInst::Create(I->getOperand(0), True, False);
8107 break;
8108 }
Chris Lattner8114b712008-06-18 04:00:49 +00008109 case Instruction::PHI: {
8110 PHINode *OPN = cast<PHINode>(I);
8111 PHINode *NPN = PHINode::Create(Ty);
8112 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8113 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8114 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8115 }
8116 Res = NPN;
8117 break;
8118 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008119 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008120 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008121 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008122 break;
8123 }
8124
Chris Lattner8114b712008-06-18 04:00:49 +00008125 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008126 return InsertNewInstBefore(Res, *I);
8127}
8128
Reid Spencer3da59db2006-11-27 01:05:10 +00008129/// @brief Implement the transforms common to all CastInst visitors.
8130Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008131 Value *Src = CI.getOperand(0);
8132
Dan Gohman23d9d272007-05-11 21:10:54 +00008133 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008134 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008135 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008136 if (Instruction::CastOps opc =
8137 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8138 // The first cast (CSrc) is eliminable so we need to fix up or replace
8139 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008140 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008141 }
8142 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008143
Reid Spencer3da59db2006-11-27 01:05:10 +00008144 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008145 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8146 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8147 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008148
8149 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008150 if (isa<PHINode>(Src))
8151 if (Instruction *NV = FoldOpIntoPhi(CI))
8152 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008153
Reid Spencer3da59db2006-11-27 01:05:10 +00008154 return 0;
8155}
8156
Chris Lattner46cd5a12009-01-09 05:44:56 +00008157/// FindElementAtOffset - Given a type and a constant offset, determine whether
8158/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008159/// the specified offset. If so, fill them into NewIndices and return the
8160/// resultant element type, otherwise return null.
8161static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8162 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008163 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008164 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008165 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008166 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008167
8168 // Start with the index over the outer type. Note that the type size
8169 // might be zero (even if the offset isn't zero) if the indexed type
8170 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008171 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008172 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008173 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008174 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008175 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008176
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008177 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008178 if (Offset < 0) {
8179 --FirstIdx;
8180 Offset += TySize;
8181 assert(Offset >= 0);
8182 }
8183 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8184 }
8185
Owen Andersoneed707b2009-07-24 23:12:02 +00008186 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008187
8188 // Index into the types. If we fail, set OrigBase to null.
8189 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008190 // Indexing into tail padding between struct/array elements.
8191 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008192 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008193
Chris Lattner46cd5a12009-01-09 05:44:56 +00008194 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8195 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008196 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8197 "Offset must stay within the indexed type");
8198
Chris Lattner46cd5a12009-01-09 05:44:56 +00008199 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008200 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008201
8202 Offset -= SL->getElementOffset(Elt);
8203 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008204 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008205 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008206 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008207 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008208 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008209 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008210 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008211 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008212 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008213 }
8214 }
8215
Chris Lattner3914f722009-01-24 01:00:13 +00008216 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008217}
8218
Chris Lattnerd3e28342007-04-27 17:44:50 +00008219/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8220Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8221 Value *Src = CI.getOperand(0);
8222
Chris Lattnerd3e28342007-04-27 17:44:50 +00008223 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008224 // If casting the result of a getelementptr instruction with no offset, turn
8225 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008226 if (GEP->hasAllZeroIndices()) {
8227 // Changing the cast operand is usually not a good idea but it is safe
8228 // here because the pointer operand is being replaced with another
8229 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00008230 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008231 CI.setOperand(0, GEP->getOperand(0));
8232 return &CI;
8233 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008234
8235 // If the GEP has a single use, and the base pointer is a bitcast, and the
8236 // GEP computes a constant offset, see if we can convert these three
8237 // instructions into fewer. This typically happens with unions and other
8238 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008239 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008240 if (GEP->hasAllConstantIndices()) {
8241 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008242 ConstantInt *OffsetV =
8243 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008244 int64_t Offset = OffsetV->getSExtValue();
8245
8246 // Get the base pointer input of the bitcast, and the type it points to.
8247 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8248 const Type *GEPIdxTy =
8249 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008250 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008251 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008252 // If we were able to index down into an element, create the GEP
8253 // and bitcast the result. This eliminates one bitcast, potentially
8254 // two.
8255 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8256 NewIndices.begin(),
8257 NewIndices.end(), "");
8258 InsertNewInstBefore(NGEP, CI);
8259 NGEP->takeName(GEP);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008260 if (cast<GEPOperator>(GEP)->isInBounds())
8261 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner9bc14642007-04-28 00:57:34 +00008262
Chris Lattner46cd5a12009-01-09 05:44:56 +00008263 if (isa<BitCastInst>(CI))
8264 return new BitCastInst(NGEP, CI.getType());
8265 assert(isa<PtrToIntInst>(CI));
8266 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008267 }
8268 }
8269 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008270 }
8271
8272 return commonCastTransforms(CI);
8273}
8274
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008275/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8276/// type like i42. We don't want to introduce operations on random non-legal
8277/// integer types where they don't already exist in the code. In the future,
8278/// we should consider making this based off target-data, so that 32-bit targets
8279/// won't get i64 operations etc.
8280static bool isSafeIntegerType(const Type *Ty) {
8281 switch (Ty->getPrimitiveSizeInBits()) {
8282 case 8:
8283 case 16:
8284 case 32:
8285 case 64:
8286 return true;
8287 default:
8288 return false;
8289 }
8290}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008291
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008292/// commonIntCastTransforms - This function implements the common transforms
8293/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008294Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8295 if (Instruction *Result = commonCastTransforms(CI))
8296 return Result;
8297
8298 Value *Src = CI.getOperand(0);
8299 const Type *SrcTy = Src->getType();
8300 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008301 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8302 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008303
Reid Spencer3da59db2006-11-27 01:05:10 +00008304 // See if we can simplify any instructions used by the LHS whose sole
8305 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008306 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008307 return &CI;
8308
8309 // If the source isn't an instruction or has more than one use then we
8310 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008311 Instruction *SrcI = dyn_cast<Instruction>(Src);
8312 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008313 return 0;
8314
Chris Lattnerc739cd62007-03-03 05:27:34 +00008315 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008316 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008317 // Only do this if the dest type is a simple type, don't convert the
8318 // expression tree to something weird like i93 unless the source is also
8319 // strange.
8320 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008321 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8322 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008323 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008324 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008325 // eliminates the cast, so it is always a win. If this is a zero-extension,
8326 // we need to do an AND to maintain the clear top-part of the computation,
8327 // so we require that the input have eliminated at least one cast. If this
8328 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008329 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008330 bool DoXForm = false;
8331 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008332 switch (CI.getOpcode()) {
8333 default:
8334 // All the others use floating point so we shouldn't actually
8335 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008336 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008337 case Instruction::Trunc:
8338 DoXForm = true;
8339 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008340 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008341 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008342 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008343 // If it's unnecessary to issue an AND to clear the high bits, it's
8344 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008345 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008346 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8347 if (MaskedValueIsZero(TryRes, Mask))
8348 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008349
8350 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008351 if (TryI->use_empty())
8352 EraseInstFromFunction(*TryI);
8353 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008354 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008355 }
Evan Chengf35fd542009-01-15 17:01:23 +00008356 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008357 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008358 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008359 // If we do not have to emit the truncate + sext pair, then it's always
8360 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008361 //
8362 // It's not safe to eliminate the trunc + sext pair if one of the
8363 // eliminated cast is a truncate. e.g.
8364 // t2 = trunc i32 t1 to i16
8365 // t3 = sext i16 t2 to i32
8366 // !=
8367 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008368 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008369 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8370 if (NumSignBits > (DestBitSize - SrcBitSize))
8371 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008372
8373 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008374 if (TryI->use_empty())
8375 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008376 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008377 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008378 }
Evan Chengf35fd542009-01-15 17:01:23 +00008379 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008380
8381 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008382 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8383 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008384 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8385 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008386 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008387 // Just replace this cast with the result.
8388 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008389
Reid Spencer3da59db2006-11-27 01:05:10 +00008390 assert(Res->getType() == DestTy);
8391 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008392 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008393 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008394 // Just replace this cast with the result.
8395 return ReplaceInstUsesWith(CI, Res);
8396 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008397 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008398
8399 // If the high bits are already zero, just replace this cast with the
8400 // result.
8401 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8402 if (MaskedValueIsZero(Res, Mask))
8403 return ReplaceInstUsesWith(CI, Res);
8404
8405 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008406 Constant *C = ConstantInt::get(*Context,
8407 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008408 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008409 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008410 case Instruction::SExt: {
8411 // If the high bits are already filled with sign bit, just replace this
8412 // cast with the result.
8413 unsigned NumSignBits = ComputeNumSignBits(Res);
8414 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008415 return ReplaceInstUsesWith(CI, Res);
8416
Reid Spencer3da59db2006-11-27 01:05:10 +00008417 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008418 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008419 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8420 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008421 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008422 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008423 }
8424 }
8425
8426 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8427 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8428
8429 switch (SrcI->getOpcode()) {
8430 case Instruction::Add:
8431 case Instruction::Mul:
8432 case Instruction::And:
8433 case Instruction::Or:
8434 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008435 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008436 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8437 // Don't insert two casts unless at least one can be eliminated.
8438 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008439 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman65445c52009-07-13 21:45:57 +00008440 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8441 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008442 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008443 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008444 }
8445 }
8446
8447 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8448 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8449 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008450 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008451 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008452 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008453 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008454 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008455 }
8456 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008457
Eli Friedman65445c52009-07-13 21:45:57 +00008458 case Instruction::Shl: {
8459 // Canonicalize trunc inside shl, if we can.
8460 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8461 if (CI && DestBitSize < SrcBitSize &&
8462 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8463 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8464 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008465 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008466 }
8467 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008468 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008469 }
8470 return 0;
8471}
8472
Chris Lattner8a9f5712007-04-11 06:57:46 +00008473Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008474 if (Instruction *Result = commonIntCastTransforms(CI))
8475 return Result;
8476
8477 Value *Src = CI.getOperand(0);
8478 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008479 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8480 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008481
8482 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008483 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008484 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008485 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersona7235ea2009-07-31 20:28:14 +00008486 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008487 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008488 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008489
Chris Lattner4f9797d2009-03-24 18:15:30 +00008490 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8491 ConstantInt *ShAmtV = 0;
8492 Value *ShiftOp = 0;
8493 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008494 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008495 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8496
8497 // Get a mask for the bits shifting in.
8498 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8499 if (MaskedValueIsZero(ShiftOp, Mask)) {
8500 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008501 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008502
8503 // Okay, we can shrink this. Truncate the input, then return a new
8504 // shift.
8505 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008506 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008507 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008508 }
8509 }
8510
8511 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008512}
8513
Evan Chengb98a10e2008-03-24 00:21:34 +00008514/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8515/// in order to eliminate the icmp.
8516Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8517 bool DoXform) {
8518 // If we are just checking for a icmp eq of a single bit and zext'ing it
8519 // to an integer, then shift the bit to the appropriate place and then
8520 // cast to integer to avoid the comparison.
8521 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8522 const APInt &Op1CV = Op1C->getValue();
8523
8524 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8525 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8526 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8527 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8528 if (!DoXform) return ICI;
8529
8530 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008531 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008532 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008533 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008534 In->getName()+".lobit"),
8535 CI);
8536 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008537 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008538 false/*ZExt*/, "tmp", &CI);
8539
8540 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008541 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008542 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008543 In->getName()+".not"),
8544 CI);
8545 }
8546
8547 return ReplaceInstUsesWith(CI, In);
8548 }
8549
8550
8551
8552 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8553 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8554 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8555 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8556 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8557 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8558 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8559 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8560 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8561 // This only works for EQ and NE
8562 ICI->isEquality()) {
8563 // If Op1C some other power of two, convert:
8564 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8565 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8566 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8567 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8568
8569 APInt KnownZeroMask(~KnownZero);
8570 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8571 if (!DoXform) return ICI;
8572
8573 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8574 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8575 // (X&4) == 2 --> false
8576 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008577 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008578 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008579 return ReplaceInstUsesWith(CI, Res);
8580 }
8581
8582 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8583 Value *In = ICI->getOperand(0);
8584 if (ShiftAmt) {
8585 // Perform a logical shr by shiftamt.
8586 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008587 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersoneed707b2009-07-24 23:12:02 +00008588 ConstantInt::get(In->getType(), ShiftAmt),
Evan Chengb98a10e2008-03-24 00:21:34 +00008589 In->getName()+".lobit"), CI);
8590 }
8591
8592 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008593 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008594 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008595 InsertNewInstBefore(cast<Instruction>(In), CI);
8596 }
8597
8598 if (CI.getType() == In->getType())
8599 return ReplaceInstUsesWith(CI, In);
8600 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008601 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008602 }
8603 }
8604 }
8605
8606 return 0;
8607}
8608
Chris Lattner8a9f5712007-04-11 06:57:46 +00008609Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008610 // If one of the common conversion will work ..
8611 if (Instruction *Result = commonIntCastTransforms(CI))
8612 return Result;
8613
8614 Value *Src = CI.getOperand(0);
8615
Chris Lattnera84f47c2009-02-17 20:47:23 +00008616 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8617 // types and if the sizes are just right we can convert this into a logical
8618 // 'and' which will be much cheaper than the pair of casts.
8619 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8620 // Get the sizes of the types involved. We know that the intermediate type
8621 // will be smaller than A or C, but don't know the relation between A and C.
8622 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008623 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8624 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8625 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008626 // If we're actually extending zero bits, then if
8627 // SrcSize < DstSize: zext(a & mask)
8628 // SrcSize == DstSize: a & mask
8629 // SrcSize > DstSize: trunc(a) & mask
8630 if (SrcSize < DstSize) {
8631 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008632 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008633 Instruction *And =
8634 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8635 InsertNewInstBefore(And, CI);
8636 return new ZExtInst(And, CI.getType());
8637 } else if (SrcSize == DstSize) {
8638 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008639 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008640 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008641 } else if (SrcSize > DstSize) {
8642 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8643 InsertNewInstBefore(Trunc, CI);
8644 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008645 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008646 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008647 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008648 }
8649 }
8650
Evan Chengb98a10e2008-03-24 00:21:34 +00008651 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8652 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008653
Evan Chengb98a10e2008-03-24 00:21:34 +00008654 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8655 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8656 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8657 // of the (zext icmp) will be transformed.
8658 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8659 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8660 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8661 (transformZExtICmp(LHS, CI, false) ||
8662 transformZExtICmp(RHS, CI, false))) {
8663 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8664 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008665 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008666 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008667 }
8668
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008669 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008670 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8671 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8672 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8673 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008674 if (TI0->getType() == CI.getType())
8675 return
8676 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008677 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008678 }
8679
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008680 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8681 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8682 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8683 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8684 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8685 And->getOperand(1) == C)
8686 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8687 Value *TI0 = TI->getOperand(0);
8688 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008689 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008690 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8691 InsertNewInstBefore(NewAnd, *And);
8692 return BinaryOperator::CreateXor(NewAnd, ZC);
8693 }
8694 }
8695
Reid Spencer3da59db2006-11-27 01:05:10 +00008696 return 0;
8697}
8698
Chris Lattner8a9f5712007-04-11 06:57:46 +00008699Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008700 if (Instruction *I = commonIntCastTransforms(CI))
8701 return I;
8702
Chris Lattner8a9f5712007-04-11 06:57:46 +00008703 Value *Src = CI.getOperand(0);
8704
Dan Gohman1975d032008-10-30 20:40:10 +00008705 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008706 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008707 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008708 Constant::getAllOnesValue(CI.getType()),
8709 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008710
8711 // See if the value being truncated is already sign extended. If so, just
8712 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008713 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008714 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008715 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8716 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8717 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008718 unsigned NumSignBits = ComputeNumSignBits(Op);
8719
8720 if (OpBits == DestBits) {
8721 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8722 // bits, it is already ready.
8723 if (NumSignBits > DestBits-MidBits)
8724 return ReplaceInstUsesWith(CI, Op);
8725 } else if (OpBits < DestBits) {
8726 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8727 // bits, just sext from i32.
8728 if (NumSignBits > OpBits-MidBits)
8729 return new SExtInst(Op, CI.getType(), "tmp");
8730 } else {
8731 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8732 // bits, just truncate to i32.
8733 if (NumSignBits > OpBits-MidBits)
8734 return new TruncInst(Op, CI.getType(), "tmp");
8735 }
8736 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008737
8738 // If the input is a shl/ashr pair of a same constant, then this is a sign
8739 // extension from a smaller value. If we could trust arbitrary bitwidth
8740 // integers, we could turn this into a truncate to the smaller bit and then
8741 // use a sext for the whole extension. Since we don't, look deeper and check
8742 // for a truncate. If the source and dest are the same type, eliminate the
8743 // trunc and extend and just do shifts. For example, turn:
8744 // %a = trunc i32 %i to i8
8745 // %b = shl i8 %a, 6
8746 // %c = ashr i8 %b, 6
8747 // %d = sext i8 %c to i32
8748 // into:
8749 // %a = shl i32 %i, 30
8750 // %d = ashr i32 %a, 30
8751 Value *A = 0;
8752 ConstantInt *BA = 0, *CA = 0;
8753 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008754 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008755 BA == CA && isa<TruncInst>(A)) {
8756 Value *I = cast<TruncInst>(A)->getOperand(0);
8757 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008758 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8759 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008760 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008761 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattner46bbad22008-08-06 07:35:52 +00008762 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8763 CI.getName()), CI);
8764 return BinaryOperator::CreateAShr(I, ShAmtV);
8765 }
8766 }
8767
Chris Lattnerba417832007-04-11 06:12:58 +00008768 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008769}
8770
Chris Lattnerb7530652008-01-27 05:29:54 +00008771/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8772/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008773static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008774 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008775 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008776 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008777 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8778 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008779 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008780 return 0;
8781}
8782
8783/// LookThroughFPExtensions - If this is an fp extension instruction, look
8784/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008785static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008786 if (Instruction *I = dyn_cast<Instruction>(V))
8787 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008788 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008789
8790 // If this value is a constant, return the constant in the smallest FP type
8791 // that can accurately represent it. This allows us to turn
8792 // (float)((double)X+2.0) into x+2.0f.
8793 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008794 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008795 return V; // No constant folding of this.
8796 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008797 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008798 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008799 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008800 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008801 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008802 return V;
8803 // Don't try to shrink to various long double types.
8804 }
8805
8806 return V;
8807}
8808
8809Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8810 if (Instruction *I = commonCastTransforms(CI))
8811 return I;
8812
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008813 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008814 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008815 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008816 // many builtins (sqrt, etc).
8817 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8818 if (OpI && OpI->hasOneUse()) {
8819 switch (OpI->getOpcode()) {
8820 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008821 case Instruction::FAdd:
8822 case Instruction::FSub:
8823 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008824 case Instruction::FDiv:
8825 case Instruction::FRem:
8826 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008827 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8828 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008829 if (LHSTrunc->getType() != SrcTy &&
8830 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008831 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008832 // If the source types were both smaller than the destination type of
8833 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008834 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8835 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008836 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8837 CI.getType(), CI);
8838 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8839 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008840 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008841 }
8842 }
8843 break;
8844 }
8845 }
8846 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008847}
8848
8849Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8850 return commonCastTransforms(CI);
8851}
8852
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008853Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008854 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8855 if (OpI == 0)
8856 return commonCastTransforms(FI);
8857
8858 // fptoui(uitofp(X)) --> X
8859 // fptoui(sitofp(X)) --> X
8860 // This is safe if the intermediate type has enough bits in its mantissa to
8861 // accurately represent all values of X. For example, do not do this with
8862 // i64->float->i64. This is also safe for sitofp case, because any negative
8863 // 'X' value would cause an undefined result for the fptoui.
8864 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8865 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008866 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008867 OpI->getType()->getFPMantissaWidth())
8868 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008869
8870 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008871}
8872
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008873Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008874 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8875 if (OpI == 0)
8876 return commonCastTransforms(FI);
8877
8878 // fptosi(sitofp(X)) --> X
8879 // fptosi(uitofp(X)) --> X
8880 // This is safe if the intermediate type has enough bits in its mantissa to
8881 // accurately represent all values of X. For example, do not do this with
8882 // i64->float->i64. This is also safe for sitofp case, because any negative
8883 // 'X' value would cause an undefined result for the fptoui.
8884 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8885 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008886 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008887 OpI->getType()->getFPMantissaWidth())
8888 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008889
8890 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008891}
8892
8893Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8894 return commonCastTransforms(CI);
8895}
8896
8897Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8898 return commonCastTransforms(CI);
8899}
8900
Chris Lattnera0e69692009-03-24 18:35:40 +00008901Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8902 // If the destination integer type is smaller than the intptr_t type for
8903 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8904 // trunc to be exposed to other transforms. Don't do this for extending
8905 // ptrtoint's, because we don't know if the target sign or zero extends its
8906 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008907 if (TD &&
8908 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008909 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
Owen Anderson1d0be152009-08-13 21:58:54 +00008910 TD->getIntPtrType(CI.getContext()),
Chris Lattnera0e69692009-03-24 18:35:40 +00008911 "tmp"), CI);
8912 return new TruncInst(P, CI.getType());
8913 }
8914
Chris Lattnerd3e28342007-04-27 17:44:50 +00008915 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008916}
8917
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008918Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008919 // If the source integer type is larger than the intptr_t type for
8920 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8921 // allows the trunc to be exposed to other transforms. Don't do this for
8922 // extending inttoptr's, because we don't know if the target sign or zero
8923 // extends to pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008924 if (TD &&
8925 CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008926 TD->getPointerSizeInBits()) {
8927 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
Owen Anderson1d0be152009-08-13 21:58:54 +00008928 TD->getIntPtrType(CI.getContext()),
Chris Lattnera0e69692009-03-24 18:35:40 +00008929 "tmp"), CI);
8930 return new IntToPtrInst(P, CI.getType());
8931 }
8932
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008933 if (Instruction *I = commonCastTransforms(CI))
8934 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008935
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008936 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008937}
8938
Chris Lattnerd3e28342007-04-27 17:44:50 +00008939Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008940 // If the operands are integer typed then apply the integer transforms,
8941 // otherwise just apply the common ones.
8942 Value *Src = CI.getOperand(0);
8943 const Type *SrcTy = Src->getType();
8944 const Type *DestTy = CI.getType();
8945
Eli Friedman7e25d452009-07-13 20:53:00 +00008946 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008947 if (Instruction *I = commonPointerCastTransforms(CI))
8948 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008949 } else {
8950 if (Instruction *Result = commonCastTransforms(CI))
8951 return Result;
8952 }
8953
8954
8955 // Get rid of casts from one type to the same type. These are useless and can
8956 // be replaced by the operand.
8957 if (DestTy == Src->getType())
8958 return ReplaceInstUsesWith(CI, Src);
8959
Reid Spencer3da59db2006-11-27 01:05:10 +00008960 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008961 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8962 const Type *DstElTy = DstPTy->getElementType();
8963 const Type *SrcElTy = SrcPTy->getElementType();
8964
Nate Begeman83ad90a2008-03-31 00:22:16 +00008965 // If the address spaces don't match, don't eliminate the bitcast, which is
8966 // required for changing types.
8967 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8968 return 0;
8969
Chris Lattnerd3e28342007-04-27 17:44:50 +00008970 // If we are casting a malloc or alloca to a pointer to a type of the same
8971 // size, rewrite the allocation instruction to allocate the "right" type.
8972 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8973 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8974 return V;
8975
Chris Lattnerd717c182007-05-05 22:32:24 +00008976 // If the source and destination are pointers, and this cast is equivalent
8977 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008978 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008979 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008980 unsigned NumZeros = 0;
8981 while (SrcElTy != DstElTy &&
8982 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8983 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8984 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8985 ++NumZeros;
8986 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008987
Chris Lattnerd3e28342007-04-27 17:44:50 +00008988 // If we found a path from the src to dest, create the getelementptr now.
8989 if (SrcElTy == DstElTy) {
8990 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008991 Instruction *GEP = GetElementPtrInst::Create(Src,
8992 Idxs.begin(), Idxs.end(), "",
8993 ((Instruction*) NULL));
8994 cast<GEPOperator>(GEP)->setIsInBounds(true);
8995 return GEP;
Chris Lattner9fb92132006-04-12 18:09:35 +00008996 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008997 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008998
Eli Friedman2451a642009-07-18 23:06:53 +00008999 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9000 if (DestVTy->getNumElements() == 1) {
9001 if (!isa<VectorType>(SrcTy)) {
9002 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
9003 DestVTy->getElementType(), CI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009004 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Owen Anderson1d0be152009-08-13 21:58:54 +00009005 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009006 }
9007 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9008 }
9009 }
9010
9011 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9012 if (SrcVTy->getNumElements() == 1) {
9013 if (!isa<VectorType>(DestTy)) {
9014 Instruction *Elem =
Owen Anderson1d0be152009-08-13 21:58:54 +00009015 ExtractElementInst::Create(Src, Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009016 InsertNewInstBefore(Elem, CI);
9017 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9018 }
9019 }
9020 }
9021
Reid Spencer3da59db2006-11-27 01:05:10 +00009022 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9023 if (SVI->hasOneUse()) {
9024 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9025 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009026 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009027 cast<VectorType>(DestTy)->getNumElements() ==
9028 SVI->getType()->getNumElements() &&
9029 SVI->getType()->getNumElements() ==
9030 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009031 CastInst *Tmp;
9032 // If either of the operands is a cast from CI.getType(), then
9033 // evaluating the shuffle in the casted destination's type will allow
9034 // us to eliminate at least one cast.
9035 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9036 Tmp->getOperand(0)->getType() == DestTy) ||
9037 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9038 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009039 Value *LHS = InsertCastBefore(Instruction::BitCast,
9040 SVI->getOperand(0), DestTy, CI);
9041 Value *RHS = InsertCastBefore(Instruction::BitCast,
9042 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009043 // Return a new shuffle vector. Use the same element ID's, as we
9044 // know the vector types match #elts.
9045 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009046 }
9047 }
9048 }
9049 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009050 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009051}
9052
Chris Lattnere576b912004-04-09 23:46:01 +00009053/// GetSelectFoldableOperands - We want to turn code that looks like this:
9054/// %C = or %A, %B
9055/// %D = select %cond, %C, %A
9056/// into:
9057/// %C = select %cond, %B, 0
9058/// %D = or %A, %C
9059///
9060/// Assuming that the specified instruction is an operand to the select, return
9061/// a bitmask indicating which operands of this instruction are foldable if they
9062/// equal the other incoming value of the select.
9063///
9064static unsigned GetSelectFoldableOperands(Instruction *I) {
9065 switch (I->getOpcode()) {
9066 case Instruction::Add:
9067 case Instruction::Mul:
9068 case Instruction::And:
9069 case Instruction::Or:
9070 case Instruction::Xor:
9071 return 3; // Can fold through either operand.
9072 case Instruction::Sub: // Can only fold on the amount subtracted.
9073 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009074 case Instruction::LShr:
9075 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009076 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009077 default:
9078 return 0; // Cannot fold
9079 }
9080}
9081
9082/// GetSelectFoldableConstant - For the same transformation as the previous
9083/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009084static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009085 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009086 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009087 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009088 case Instruction::Add:
9089 case Instruction::Sub:
9090 case Instruction::Or:
9091 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009092 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009093 case Instruction::LShr:
9094 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009095 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009096 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009097 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009098 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009099 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009100 }
9101}
9102
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009103/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9104/// have the same opcode and only one use each. Try to simplify this.
9105Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9106 Instruction *FI) {
9107 if (TI->getNumOperands() == 1) {
9108 // If this is a non-volatile load or a cast from the same type,
9109 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009110 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009111 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9112 return 0;
9113 } else {
9114 return 0; // unknown unary op.
9115 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009116
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009117 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009118 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009119 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009120 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009121 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009122 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009123 }
9124
Reid Spencer832254e2007-02-02 02:16:23 +00009125 // Only handle binary operators here.
9126 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009127 return 0;
9128
9129 // Figure out if the operations have any operands in common.
9130 Value *MatchOp, *OtherOpT, *OtherOpF;
9131 bool MatchIsOpZero;
9132 if (TI->getOperand(0) == FI->getOperand(0)) {
9133 MatchOp = TI->getOperand(0);
9134 OtherOpT = TI->getOperand(1);
9135 OtherOpF = FI->getOperand(1);
9136 MatchIsOpZero = true;
9137 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9138 MatchOp = TI->getOperand(1);
9139 OtherOpT = TI->getOperand(0);
9140 OtherOpF = FI->getOperand(0);
9141 MatchIsOpZero = false;
9142 } else if (!TI->isCommutative()) {
9143 return 0;
9144 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9145 MatchOp = TI->getOperand(0);
9146 OtherOpT = TI->getOperand(1);
9147 OtherOpF = FI->getOperand(0);
9148 MatchIsOpZero = true;
9149 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9150 MatchOp = TI->getOperand(1);
9151 OtherOpT = TI->getOperand(0);
9152 OtherOpF = FI->getOperand(1);
9153 MatchIsOpZero = true;
9154 } else {
9155 return 0;
9156 }
9157
9158 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009159 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9160 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009161 InsertNewInstBefore(NewSI, SI);
9162
9163 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9164 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009165 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009166 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009167 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009168 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009169 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009170 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009171}
9172
Evan Chengde621922009-03-31 20:42:45 +00009173static bool isSelect01(Constant *C1, Constant *C2) {
9174 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9175 if (!C1I)
9176 return false;
9177 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9178 if (!C2I)
9179 return false;
9180 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9181}
9182
9183/// FoldSelectIntoOp - Try fold the select into one of the operands to
9184/// facilitate further optimization.
9185Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9186 Value *FalseVal) {
9187 // See the comment above GetSelectFoldableOperands for a description of the
9188 // transformation we are doing here.
9189 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9190 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9191 !isa<Constant>(FalseVal)) {
9192 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9193 unsigned OpToFold = 0;
9194 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9195 OpToFold = 1;
9196 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9197 OpToFold = 2;
9198 }
9199
9200 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009201 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009202 Value *OOp = TVI->getOperand(2-OpToFold);
9203 // Avoid creating select between 2 constants unless it's selecting
9204 // between 0 and 1.
9205 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9206 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9207 InsertNewInstBefore(NewSel, SI);
9208 NewSel->takeName(TVI);
9209 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9210 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009211 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009212 }
9213 }
9214 }
9215 }
9216 }
9217
9218 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9219 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9220 !isa<Constant>(TrueVal)) {
9221 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9222 unsigned OpToFold = 0;
9223 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9224 OpToFold = 1;
9225 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9226 OpToFold = 2;
9227 }
9228
9229 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009230 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009231 Value *OOp = FVI->getOperand(2-OpToFold);
9232 // Avoid creating select between 2 constants unless it's selecting
9233 // between 0 and 1.
9234 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9235 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9236 InsertNewInstBefore(NewSel, SI);
9237 NewSel->takeName(FVI);
9238 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9239 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009240 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009241 }
9242 }
9243 }
9244 }
9245 }
9246
9247 return 0;
9248}
9249
Dan Gohman81b28ce2008-09-16 18:46:06 +00009250/// visitSelectInstWithICmp - Visit a SelectInst that has an
9251/// ICmpInst as its first operand.
9252///
9253Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9254 ICmpInst *ICI) {
9255 bool Changed = false;
9256 ICmpInst::Predicate Pred = ICI->getPredicate();
9257 Value *CmpLHS = ICI->getOperand(0);
9258 Value *CmpRHS = ICI->getOperand(1);
9259 Value *TrueVal = SI.getTrueValue();
9260 Value *FalseVal = SI.getFalseValue();
9261
9262 // Check cases where the comparison is with a constant that
9263 // can be adjusted to fit the min/max idiom. We may edit ICI in
9264 // place here, so make sure the select is the only user.
9265 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009266 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009267 switch (Pred) {
9268 default: break;
9269 case ICmpInst::ICMP_ULT:
9270 case ICmpInst::ICMP_SLT: {
9271 // X < MIN ? T : F --> F
9272 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9273 return ReplaceInstUsesWith(SI, FalseVal);
9274 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009275 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009276 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9277 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9278 Pred = ICmpInst::getSwappedPredicate(Pred);
9279 CmpRHS = AdjustedRHS;
9280 std::swap(FalseVal, TrueVal);
9281 ICI->setPredicate(Pred);
9282 ICI->setOperand(1, CmpRHS);
9283 SI.setOperand(1, TrueVal);
9284 SI.setOperand(2, FalseVal);
9285 Changed = true;
9286 }
9287 break;
9288 }
9289 case ICmpInst::ICMP_UGT:
9290 case ICmpInst::ICMP_SGT: {
9291 // X > MAX ? T : F --> F
9292 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9293 return ReplaceInstUsesWith(SI, FalseVal);
9294 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009295 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009296 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9297 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9298 Pred = ICmpInst::getSwappedPredicate(Pred);
9299 CmpRHS = AdjustedRHS;
9300 std::swap(FalseVal, TrueVal);
9301 ICI->setPredicate(Pred);
9302 ICI->setOperand(1, CmpRHS);
9303 SI.setOperand(1, TrueVal);
9304 SI.setOperand(2, FalseVal);
9305 Changed = true;
9306 }
9307 break;
9308 }
9309 }
9310
Dan Gohman1975d032008-10-30 20:40:10 +00009311 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9312 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009313 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009314 if (match(TrueVal, m_ConstantInt<-1>()) &&
9315 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009316 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009317 else if (match(TrueVal, m_ConstantInt<0>()) &&
9318 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009319 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9320
Dan Gohman1975d032008-10-30 20:40:10 +00009321 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9322 // If we are just checking for a icmp eq of a single bit and zext'ing it
9323 // to an integer, then shift the bit to the appropriate place and then
9324 // cast to integer to avoid the comparison.
9325 const APInt &Op1CV = CI->getValue();
9326
9327 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9328 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9329 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009330 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009331 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009332 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009333 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009334 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009335 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009336 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009337 if (In->getType() != SI.getType())
9338 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009339 true/*SExt*/, "tmp", ICI);
9340
9341 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009342 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009343 In->getName()+".not"), *ICI);
9344
9345 return ReplaceInstUsesWith(SI, In);
9346 }
9347 }
9348 }
9349
Dan Gohman81b28ce2008-09-16 18:46:06 +00009350 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9351 // Transform (X == Y) ? X : Y -> Y
9352 if (Pred == ICmpInst::ICMP_EQ)
9353 return ReplaceInstUsesWith(SI, FalseVal);
9354 // Transform (X != Y) ? X : Y -> X
9355 if (Pred == ICmpInst::ICMP_NE)
9356 return ReplaceInstUsesWith(SI, TrueVal);
9357 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9358
9359 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9360 // Transform (X == Y) ? Y : X -> X
9361 if (Pred == ICmpInst::ICMP_EQ)
9362 return ReplaceInstUsesWith(SI, FalseVal);
9363 // Transform (X != Y) ? Y : X -> Y
9364 if (Pred == ICmpInst::ICMP_NE)
9365 return ReplaceInstUsesWith(SI, TrueVal);
9366 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9367 }
9368
9369 /// NOTE: if we wanted to, this is where to detect integer ABS
9370
9371 return Changed ? &SI : 0;
9372}
9373
Chris Lattner3d69f462004-03-12 05:52:32 +00009374Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009375 Value *CondVal = SI.getCondition();
9376 Value *TrueVal = SI.getTrueValue();
9377 Value *FalseVal = SI.getFalseValue();
9378
9379 // select true, X, Y -> X
9380 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009381 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009382 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009383
9384 // select C, X, X -> X
9385 if (TrueVal == FalseVal)
9386 return ReplaceInstUsesWith(SI, TrueVal);
9387
Chris Lattnere87597f2004-10-16 18:11:37 +00009388 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9389 return ReplaceInstUsesWith(SI, FalseVal);
9390 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9391 return ReplaceInstUsesWith(SI, TrueVal);
9392 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9393 if (isa<Constant>(TrueVal))
9394 return ReplaceInstUsesWith(SI, TrueVal);
9395 else
9396 return ReplaceInstUsesWith(SI, FalseVal);
9397 }
9398
Owen Anderson1d0be152009-08-13 21:58:54 +00009399 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009400 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009401 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009402 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009403 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009404 } else {
9405 // Change: A = select B, false, C --> A = and !B, C
9406 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009407 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009408 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009409 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009410 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009411 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009412 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009413 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009414 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009415 } else {
9416 // Change: A = select B, C, true --> A = or !B, C
9417 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009418 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009419 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009420 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009421 }
9422 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009423
9424 // select a, b, a -> a&b
9425 // select a, a, b -> a|b
9426 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009427 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009428 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009429 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009430 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009431
Chris Lattner2eefe512004-04-09 19:05:30 +00009432 // Selecting between two integer constants?
9433 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9434 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009435 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009436 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009437 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009438 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009439 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009440 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009441 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009442 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009443 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009444 }
Chris Lattner457dd822004-06-09 07:59:58 +00009445
Reid Spencere4d87aa2006-12-23 06:05:41 +00009446 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009447 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009448 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009449 // non-constant value, eliminate this whole mess. This corresponds to
9450 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009451 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009452 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009453 cast<Constant>(IC->getOperand(1))->isNullValue())
9454 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9455 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009456 isa<ConstantInt>(ICA->getOperand(1)) &&
9457 (ICA->getOperand(1) == TrueValC ||
9458 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009459 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9460 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009461 // know whether we have a icmp_ne or icmp_eq and whether the
9462 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009463 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009464 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009465 Value *V = ICA;
9466 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009467 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009468 Instruction::Xor, V, ICA->getOperand(1)), SI);
9469 return ReplaceInstUsesWith(SI, V);
9470 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009471 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009472 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009473
9474 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009475 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9476 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009477 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009478 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9479 // This is not safe in general for floating point:
9480 // consider X== -0, Y== +0.
9481 // It becomes safe if either operand is a nonzero constant.
9482 ConstantFP *CFPt, *CFPf;
9483 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9484 !CFPt->getValueAPF().isZero()) ||
9485 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9486 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009487 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009488 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009489 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009490 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009491 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009492 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009493
Reid Spencere4d87aa2006-12-23 06:05:41 +00009494 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009495 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009496 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9497 // This is not safe in general for floating point:
9498 // consider X== -0, Y== +0.
9499 // It becomes safe if either operand is a nonzero constant.
9500 ConstantFP *CFPt, *CFPf;
9501 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9502 !CFPt->getValueAPF().isZero()) ||
9503 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9504 !CFPf->getValueAPF().isZero()))
9505 return ReplaceInstUsesWith(SI, FalseVal);
9506 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009507 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009508 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9509 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009510 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009511 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009512 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009513 }
9514
9515 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009516 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9517 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9518 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009519
Chris Lattner87875da2005-01-13 22:52:24 +00009520 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9521 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9522 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009523 Instruction *AddOp = 0, *SubOp = 0;
9524
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009525 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9526 if (TI->getOpcode() == FI->getOpcode())
9527 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9528 return IV;
9529
9530 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9531 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009532 if ((TI->getOpcode() == Instruction::Sub &&
9533 FI->getOpcode() == Instruction::Add) ||
9534 (TI->getOpcode() == Instruction::FSub &&
9535 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009536 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009537 } else if ((FI->getOpcode() == Instruction::Sub &&
9538 TI->getOpcode() == Instruction::Add) ||
9539 (FI->getOpcode() == Instruction::FSub &&
9540 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009541 AddOp = TI; SubOp = FI;
9542 }
9543
9544 if (AddOp) {
9545 Value *OtherAddOp = 0;
9546 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9547 OtherAddOp = AddOp->getOperand(1);
9548 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9549 OtherAddOp = AddOp->getOperand(0);
9550 }
9551
9552 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009553 // So at this point we know we have (Y -> OtherAddOp):
9554 // select C, (add X, Y), (sub X, Z)
9555 Value *NegVal; // Compute -Z
9556 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009557 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009558 } else {
9559 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009560 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009561 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009562 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009563
9564 Value *NewTrueOp = OtherAddOp;
9565 Value *NewFalseOp = NegVal;
9566 if (AddOp != TI)
9567 std::swap(NewTrueOp, NewFalseOp);
9568 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009569 SelectInst::Create(CondVal, NewTrueOp,
9570 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009571
9572 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009573 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009574 }
9575 }
9576 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009577
Chris Lattnere576b912004-04-09 23:46:01 +00009578 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009579 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009580 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9581 if (FoldI)
9582 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009583 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009584
9585 if (BinaryOperator::isNot(CondVal)) {
9586 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9587 SI.setOperand(1, FalseVal);
9588 SI.setOperand(2, TrueVal);
9589 return &SI;
9590 }
9591
Chris Lattner3d69f462004-03-12 05:52:32 +00009592 return 0;
9593}
9594
Dan Gohmaneee962e2008-04-10 18:43:06 +00009595/// EnforceKnownAlignment - If the specified pointer points to an object that
9596/// we control, modify the object's alignment to PrefAlign. This isn't
9597/// often possible though. If alignment is important, a more reliable approach
9598/// is to simply align all global variables and allocation instructions to
9599/// their preferred alignment from the beginning.
9600///
9601static unsigned EnforceKnownAlignment(Value *V,
9602 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009603
Dan Gohmaneee962e2008-04-10 18:43:06 +00009604 User *U = dyn_cast<User>(V);
9605 if (!U) return Align;
9606
Dan Gohmanca178902009-07-17 20:47:02 +00009607 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009608 default: break;
9609 case Instruction::BitCast:
9610 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9611 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009612 // If all indexes are zero, it is just the alignment of the base pointer.
9613 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009614 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009615 if (!isa<Constant>(*i) ||
9616 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009617 AllZeroOperands = false;
9618 break;
9619 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009620
9621 if (AllZeroOperands) {
9622 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009623 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009624 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009625 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009626 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009627 }
9628
9629 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9630 // If there is a large requested alignment and we can, bump up the alignment
9631 // of the global.
9632 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009633 if (GV->getAlignment() >= PrefAlign)
9634 Align = GV->getAlignment();
9635 else {
9636 GV->setAlignment(PrefAlign);
9637 Align = PrefAlign;
9638 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009639 }
9640 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9641 // If there is a requested alignment and if this is an alloca, round up. We
9642 // don't do this for malloc, because some systems can't respect the request.
9643 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009644 if (AI->getAlignment() >= PrefAlign)
9645 Align = AI->getAlignment();
9646 else {
9647 AI->setAlignment(PrefAlign);
9648 Align = PrefAlign;
9649 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009650 }
9651 }
9652
9653 return Align;
9654}
9655
9656/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9657/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9658/// and it is more than the alignment of the ultimate object, see if we can
9659/// increase the alignment of the ultimate object, making this check succeed.
9660unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9661 unsigned PrefAlign) {
9662 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9663 sizeof(PrefAlign) * CHAR_BIT;
9664 APInt Mask = APInt::getAllOnesValue(BitWidth);
9665 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9666 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9667 unsigned TrailZ = KnownZero.countTrailingOnes();
9668 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9669
9670 if (PrefAlign > Align)
9671 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9672
9673 // We don't need to make any adjustment.
9674 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009675}
9676
Chris Lattnerf497b022008-01-13 23:50:23 +00009677Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009678 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009679 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009680 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009681 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009682
9683 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009684 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009685 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009686 return MI;
9687 }
9688
9689 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9690 // load/store.
9691 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9692 if (MemOpLength == 0) return 0;
9693
Chris Lattner37ac6082008-01-14 00:28:35 +00009694 // Source and destination pointer types are always "i8*" for intrinsic. See
9695 // if the size is something we can handle with a single primitive load/store.
9696 // A single load+store correctly handles overlapping memory in the memmove
9697 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009698 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009699 if (Size == 0) return MI; // Delete this mem transfer.
9700
9701 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009702 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009703
Chris Lattner37ac6082008-01-14 00:28:35 +00009704 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009705 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009706 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009707
9708 // Memcpy forces the use of i8* for the source and destination. That means
9709 // that if you're using memcpy to move one double around, you'll get a cast
9710 // from double* to i8*. We'd much rather use a double load+store rather than
9711 // an i64 load+store, here because this improves the odds that the source or
9712 // dest address will be promotable. See if we can find a better type than the
9713 // integer datatype.
9714 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9715 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009716 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009717 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9718 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009719 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009720 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9721 if (STy->getNumElements() == 1)
9722 SrcETy = STy->getElementType(0);
9723 else
9724 break;
9725 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9726 if (ATy->getNumElements() == 1)
9727 SrcETy = ATy->getElementType();
9728 else
9729 break;
9730 } else
9731 break;
9732 }
9733
Dan Gohman8f8e2692008-05-23 01:52:21 +00009734 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009735 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009736 }
9737 }
9738
9739
Chris Lattnerf497b022008-01-13 23:50:23 +00009740 // If the memcpy/memmove provides better alignment info than we can
9741 // infer, use it.
9742 SrcAlign = std::max(SrcAlign, CopyAlign);
9743 DstAlign = std::max(DstAlign, CopyAlign);
9744
9745 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9746 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009747 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9748 InsertNewInstBefore(L, *MI);
9749 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9750
9751 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009752 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009753 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009754}
Chris Lattner3d69f462004-03-12 05:52:32 +00009755
Chris Lattner69ea9d22008-04-30 06:39:11 +00009756Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9757 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009758 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009759 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009760 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009761 return MI;
9762 }
9763
9764 // Extract the length and alignment and fill if they are constant.
9765 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9766 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009767 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009768 return 0;
9769 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009770 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009771
9772 // If the length is zero, this is a no-op
9773 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9774
9775 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9776 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009777 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009778
9779 Value *Dest = MI->getDest();
Owen Andersondebcb012009-07-29 22:17:13 +00009780 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009781
9782 // Alignment 0 is identity for alignment 1 for memset, but not store.
9783 if (Alignment == 0) Alignment = 1;
9784
9785 // Extract the fill value and store.
9786 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009787 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009788 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009789
9790 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009791 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009792 return MI;
9793 }
9794
9795 return 0;
9796}
9797
9798
Chris Lattner8b0ea312006-01-13 20:11:04 +00009799/// visitCallInst - CallInst simplification. This mostly only handles folding
9800/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9801/// the heavy lifting.
9802///
Chris Lattner9fe38862003-06-19 17:00:31 +00009803Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009804 // If the caller function is nounwind, mark the call as nounwind, even if the
9805 // callee isn't.
9806 if (CI.getParent()->getParent()->doesNotThrow() &&
9807 !CI.doesNotThrow()) {
9808 CI.setDoesNotThrow();
9809 return &CI;
9810 }
9811
9812
9813
Chris Lattner8b0ea312006-01-13 20:11:04 +00009814 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9815 if (!II) return visitCallSite(&CI);
9816
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009817 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9818 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009819 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009820 bool Changed = false;
9821
9822 // memmove/cpy/set of zero bytes is a noop.
9823 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9824 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9825
Chris Lattner35b9e482004-10-12 04:52:52 +00009826 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009827 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009828 // Replace the instruction with just byte operations. We would
9829 // transform other cases to loads/stores, but we don't know if
9830 // alignment is sufficient.
9831 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009832 }
9833
Chris Lattner35b9e482004-10-12 04:52:52 +00009834 // If we have a memmove and the source operation is a constant global,
9835 // then the source and dest pointers can't alias, so we can change this
9836 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009837 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009838 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9839 if (GVSrc->isConstant()) {
9840 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009841 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9842 const Type *Tys[1];
9843 Tys[0] = CI.getOperand(3)->getType();
9844 CI.setOperand(0,
9845 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009846 Changed = true;
9847 }
Chris Lattnera935db82008-05-28 05:30:41 +00009848
9849 // memmove(x,x,size) -> noop.
9850 if (MMI->getSource() == MMI->getDest())
9851 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009852 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009853
Chris Lattner95a959d2006-03-06 20:18:44 +00009854 // If we can determine a pointer alignment that is bigger than currently
9855 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009856 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009857 if (Instruction *I = SimplifyMemTransfer(MI))
9858 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009859 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9860 if (Instruction *I = SimplifyMemSet(MSI))
9861 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009862 }
9863
Chris Lattner8b0ea312006-01-13 20:11:04 +00009864 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009865 }
9866
9867 switch (II->getIntrinsicID()) {
9868 default: break;
9869 case Intrinsic::bswap:
9870 // bswap(bswap(x)) -> x
9871 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9872 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9873 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9874 break;
9875 case Intrinsic::ppc_altivec_lvx:
9876 case Intrinsic::ppc_altivec_lvxl:
9877 case Intrinsic::x86_sse_loadu_ps:
9878 case Intrinsic::x86_sse2_loadu_pd:
9879 case Intrinsic::x86_sse2_loadu_dq:
9880 // Turn PPC lvx -> load if the pointer is known aligned.
9881 // Turn X86 loadups -> load if the pointer is known aligned.
9882 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9883 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersondebcb012009-07-29 22:17:13 +00009884 PointerType::getUnqual(II->getType()),
Chris Lattner0521e3c2008-06-18 04:33:20 +00009885 CI);
9886 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009887 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009888 break;
9889 case Intrinsic::ppc_altivec_stvx:
9890 case Intrinsic::ppc_altivec_stvxl:
9891 // Turn stvx -> store if the pointer is known aligned.
9892 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9893 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009894 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009895 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9896 return new StoreInst(II->getOperand(1), Ptr);
9897 }
9898 break;
9899 case Intrinsic::x86_sse_storeu_ps:
9900 case Intrinsic::x86_sse2_storeu_pd:
9901 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009902 // Turn X86 storeu -> store if the pointer is known aligned.
9903 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9904 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009905 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009906 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9907 return new StoreInst(II->getOperand(2), Ptr);
9908 }
9909 break;
9910
9911 case Intrinsic::x86_sse_cvttss2si: {
9912 // These intrinsics only demands the 0th element of its input vector. If
9913 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009914 unsigned VWidth =
9915 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9916 APInt DemandedElts(VWidth, 1);
9917 APInt UndefElts(VWidth, 0);
9918 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009919 UndefElts)) {
9920 II->setOperand(1, V);
9921 return II;
9922 }
9923 break;
9924 }
9925
9926 case Intrinsic::ppc_altivec_vperm:
9927 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9928 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9929 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009930
Chris Lattner0521e3c2008-06-18 04:33:20 +00009931 // Check that all of the elements are integer constants or undefs.
9932 bool AllEltsOk = true;
9933 for (unsigned i = 0; i != 16; ++i) {
9934 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9935 !isa<UndefValue>(Mask->getOperand(i))) {
9936 AllEltsOk = false;
9937 break;
9938 }
9939 }
9940
9941 if (AllEltsOk) {
9942 // Cast the input vectors to byte vectors.
9943 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9944 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009945 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009946
Chris Lattner0521e3c2008-06-18 04:33:20 +00009947 // Only extract each element once.
9948 Value *ExtractedElts[32];
9949 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9950
Chris Lattnere2ed0572006-04-06 19:19:17 +00009951 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009952 if (isa<UndefValue>(Mask->getOperand(i)))
9953 continue;
9954 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9955 Idx &= 31; // Match the hardware behavior.
9956
9957 if (ExtractedElts[Idx] == 0) {
9958 Instruction *Elt =
Eric Christophera3500da2009-07-25 02:28:41 +00009959 ExtractElementInst::Create(Idx < 16 ? Op0 : Op1,
Owen Anderson1d0be152009-08-13 21:58:54 +00009960 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false), "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009961 InsertNewInstBefore(Elt, CI);
9962 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009963 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009964
Chris Lattner0521e3c2008-06-18 04:33:20 +00009965 // Insert this value into the result vector.
9966 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
Owen Anderson1d0be152009-08-13 21:58:54 +00009967 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009968 "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009969 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009970 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009971 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009972 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009973 }
9974 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009975
Chris Lattner0521e3c2008-06-18 04:33:20 +00009976 case Intrinsic::stackrestore: {
9977 // If the save is right next to the restore, remove the restore. This can
9978 // happen when variable allocas are DCE'd.
9979 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9980 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9981 BasicBlock::iterator BI = SS;
9982 if (&*++BI == II)
9983 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009984 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009985 }
9986
9987 // Scan down this block to see if there is another stack restore in the
9988 // same block without an intervening call/alloca.
9989 BasicBlock::iterator BI = II;
9990 TerminatorInst *TI = II->getParent()->getTerminator();
9991 bool CannotRemove = false;
9992 for (++BI; &*BI != TI; ++BI) {
9993 if (isa<AllocaInst>(BI)) {
9994 CannotRemove = true;
9995 break;
9996 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009997 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9998 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9999 // If there is a stackrestore below this one, remove this one.
10000 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10001 return EraseInstFromFunction(CI);
10002 // Otherwise, ignore the intrinsic.
10003 } else {
10004 // If we found a non-intrinsic call, we can't remove the stack
10005 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010006 CannotRemove = true;
10007 break;
10008 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010009 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010010 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010011
10012 // If the stack restore is in a return/unwind block and if there are no
10013 // allocas or calls between the restore and the return, nuke the restore.
10014 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10015 return EraseInstFromFunction(CI);
10016 break;
10017 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010018 }
10019
Chris Lattner8b0ea312006-01-13 20:11:04 +000010020 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010021}
10022
10023// InvokeInst simplification
10024//
10025Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010026 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010027}
10028
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010029/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10030/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010031static bool isSafeToEliminateVarargsCast(const CallSite CS,
10032 const CastInst * const CI,
10033 const TargetData * const TD,
10034 const int ix) {
10035 if (!CI->isLosslessCast())
10036 return false;
10037
10038 // The size of ByVal arguments is derived from the type, so we
10039 // can't change to a type with a different size. If the size were
10040 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010041 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010042 return true;
10043
10044 const Type* SrcTy =
10045 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10046 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10047 if (!SrcTy->isSized() || !DstTy->isSized())
10048 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010049 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010050 return false;
10051 return true;
10052}
10053
Chris Lattnera44d8a22003-10-07 22:32:43 +000010054// visitCallSite - Improvements for call and invoke instructions.
10055//
10056Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010057 bool Changed = false;
10058
10059 // If the callee is a constexpr cast of a function, attempt to move the cast
10060 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010061 if (transformConstExprCastCall(CS)) return 0;
10062
Chris Lattner6c266db2003-10-07 22:54:13 +000010063 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010064
Chris Lattner08b22ec2005-05-13 07:09:09 +000010065 if (Function *CalleeF = dyn_cast<Function>(Callee))
10066 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10067 Instruction *OldCall = CS.getInstruction();
10068 // If the call and callee calling conventions don't match, this call must
10069 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010070 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +000010071 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Owen Andersond672ecb2009-07-03 00:17:18 +000010072 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +000010073 if (!OldCall->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010074 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010075 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10076 return EraseInstFromFunction(*OldCall);
10077 return 0;
10078 }
10079
Chris Lattner17be6352004-10-18 02:59:09 +000010080 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10081 // This instruction is not reachable, just remove it. We insert a store to
10082 // undef so that we know that this code is not reachable, despite the fact
10083 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010084 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +000010085 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Chris Lattner17be6352004-10-18 02:59:09 +000010086 CS.getInstruction());
10087
10088 if (!CS.getInstruction()->use_empty())
10089 CS.getInstruction()->
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010090 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010091
10092 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10093 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010094 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010095 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010096 }
Chris Lattner17be6352004-10-18 02:59:09 +000010097 return EraseInstFromFunction(*CS.getInstruction());
10098 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010099
Duncan Sandscdb6d922007-09-17 10:26:40 +000010100 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10101 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10102 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10103 return transformCallThroughTrampoline(CS);
10104
Chris Lattner6c266db2003-10-07 22:54:13 +000010105 const PointerType *PTy = cast<PointerType>(Callee->getType());
10106 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10107 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010108 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010109 // See if we can optimize any arguments passed through the varargs area of
10110 // the call.
10111 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010112 E = CS.arg_end(); I != E; ++I, ++ix) {
10113 CastInst *CI = dyn_cast<CastInst>(*I);
10114 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10115 *I = CI->getOperand(0);
10116 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010117 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010118 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010119 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010120
Duncan Sandsf0c33542007-12-19 21:13:37 +000010121 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010122 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010123 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010124 Changed = true;
10125 }
10126
Chris Lattner6c266db2003-10-07 22:54:13 +000010127 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010128}
10129
Chris Lattner9fe38862003-06-19 17:00:31 +000010130// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10131// attempt to move the cast to the arguments of the call/invoke.
10132//
10133bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10134 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10135 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010136 if (CE->getOpcode() != Instruction::BitCast ||
10137 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010138 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010139 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010140 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010141 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010142
10143 // Okay, this is a cast from a function to a different type. Unless doing so
10144 // would cause a type conversion of one of our arguments, change this call to
10145 // be a direct call with arguments casted to the appropriate types.
10146 //
10147 const FunctionType *FT = Callee->getFunctionType();
10148 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010149 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010150
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010151 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010152 return false; // TODO: Handle multiple return values.
10153
Chris Lattnerf78616b2004-01-14 06:06:08 +000010154 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010155 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010156 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010157 // Conversion is ok if changing from one pointer type to another or from
10158 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010159 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010160 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010161 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010162 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010163 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010164
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010165 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010166 // void -> non-void is handled specially
Owen Anderson1d0be152009-08-13 21:58:54 +000010167 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010168 return false; // Cannot transform this return value.
10169
Chris Lattner58d74912008-03-12 17:45:29 +000010170 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010171 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010172 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010173 return false; // Attribute not compatible with transformed value.
10174 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010175
Chris Lattnerf78616b2004-01-14 06:06:08 +000010176 // If the callsite is an invoke instruction, and the return value is used by
10177 // a PHI node in a successor, we cannot change the return type of the call
10178 // because there is no place to put the cast instruction (without breaking
10179 // the critical edge). Bail out in this case.
10180 if (!Caller->use_empty())
10181 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10182 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10183 UI != E; ++UI)
10184 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10185 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010186 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010187 return false;
10188 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010189
10190 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10191 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010192
Chris Lattner9fe38862003-06-19 17:00:31 +000010193 CallSite::arg_iterator AI = CS.arg_begin();
10194 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10195 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010196 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010197
10198 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010199 return false; // Cannot transform this parameter value.
10200
Devang Patel19c87462008-09-26 22:53:05 +000010201 if (CallerPAL.getParamAttributes(i + 1)
10202 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010203 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010204
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010205 // Converting from one pointer type to another or between a pointer and an
10206 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010207 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010208 (TD && ((isa<PointerType>(ParamTy) ||
10209 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10210 (isa<PointerType>(ActTy) ||
10211 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010212 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010213 }
10214
10215 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010216 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010217 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010218
Chris Lattner58d74912008-03-12 17:45:29 +000010219 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10220 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010221 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010222 // won't be dropping them. Check that these extra arguments have attributes
10223 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010224 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10225 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010226 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010227 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010228 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010229 return false;
10230 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010231
Chris Lattner9fe38862003-06-19 17:00:31 +000010232 // Okay, we decided that this is a safe thing to do: go ahead and start
10233 // inserting cast instructions as necessary...
10234 std::vector<Value*> Args;
10235 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010236 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010237 attrVec.reserve(NumCommonArgs);
10238
10239 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010240 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010241
10242 // If the return value is not being used, the type may not be compatible
10243 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010244 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010245
10246 // Add the new return attributes.
10247 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010248 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010249
10250 AI = CS.arg_begin();
10251 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10252 const Type *ParamTy = FT->getParamType(i);
10253 if ((*AI)->getType() == ParamTy) {
10254 Args.push_back(*AI);
10255 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010256 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010257 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010258 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010259 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010260 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010261
10262 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010263 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010264 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010265 }
10266
10267 // If the function takes more arguments than the call was taking, add them
10268 // now...
10269 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010270 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010271
10272 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010273 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010274 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010275 errs() << "WARNING: While resolving call to function '"
10276 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010277 } else {
10278 // Add all of the arguments in their promoted form to the arg list...
10279 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10280 const Type *PTy = getPromotedType((*AI)->getType());
10281 if (PTy != (*AI)->getType()) {
10282 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010283 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10284 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010285 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010286 InsertNewInstBefore(Cast, *Caller);
10287 Args.push_back(Cast);
10288 } else {
10289 Args.push_back(*AI);
10290 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010291
Duncan Sandse1e520f2008-01-13 08:02:44 +000010292 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010293 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010294 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010295 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010296 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010297 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010298
Devang Patel19c87462008-09-26 22:53:05 +000010299 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10300 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10301
Owen Anderson1d0be152009-08-13 21:58:54 +000010302 if (NewRetTy == Type::getVoidTy(*Context))
Chris Lattner6934a042007-02-11 01:23:03 +000010303 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010304
Eric Christophera66297a2009-07-25 02:45:27 +000010305 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10306 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010307
Chris Lattner9fe38862003-06-19 17:00:31 +000010308 Instruction *NC;
10309 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010310 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010311 Args.begin(), Args.end(),
10312 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010313 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010314 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010315 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010316 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10317 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010318 CallInst *CI = cast<CallInst>(Caller);
10319 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010320 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010321 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010322 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010323 }
10324
Chris Lattner6934a042007-02-11 01:23:03 +000010325 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010326 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010327 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010328 if (NV->getType() != Type::getVoidTy(*Context)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010329 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010330 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010331 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010332
10333 // If this is an invoke instruction, we should insert it after the first
10334 // non-phi, instruction in the normal successor block.
10335 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010336 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010337 InsertNewInstBefore(NC, *I);
10338 } else {
10339 // Otherwise, it's a call, just insert cast right after the call instr
10340 InsertNewInstBefore(NC, *Caller);
10341 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010342 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010343 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010344 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010345 }
10346 }
10347
Owen Anderson1d0be152009-08-13 21:58:54 +000010348 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010349 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010350 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010351 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010352 return true;
10353}
10354
Duncan Sandscdb6d922007-09-17 10:26:40 +000010355// transformCallThroughTrampoline - Turn a call to a function created by the
10356// init_trampoline intrinsic into a direct call to the underlying function.
10357//
10358Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10359 Value *Callee = CS.getCalledValue();
10360 const PointerType *PTy = cast<PointerType>(Callee->getType());
10361 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010362 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010363
10364 // If the call already has the 'nest' attribute somewhere then give up -
10365 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010366 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010367 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010368
10369 IntrinsicInst *Tramp =
10370 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10371
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010372 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010373 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10374 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10375
Devang Patel05988662008-09-25 21:00:45 +000010376 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010377 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010378 unsigned NestIdx = 1;
10379 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010380 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010381
10382 // Look for a parameter marked with the 'nest' attribute.
10383 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10384 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010385 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010386 // Record the parameter type and any other attributes.
10387 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010388 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010389 break;
10390 }
10391
10392 if (NestTy) {
10393 Instruction *Caller = CS.getInstruction();
10394 std::vector<Value*> NewArgs;
10395 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10396
Devang Patel05988662008-09-25 21:00:45 +000010397 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010398 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010399
Duncan Sandscdb6d922007-09-17 10:26:40 +000010400 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010401 // mean appending it. Likewise for attributes.
10402
Devang Patel19c87462008-09-26 22:53:05 +000010403 // Add any result attributes.
10404 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010405 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010406
Duncan Sandscdb6d922007-09-17 10:26:40 +000010407 {
10408 unsigned Idx = 1;
10409 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10410 do {
10411 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010412 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010413 Value *NestVal = Tramp->getOperand(3);
10414 if (NestVal->getType() != NestTy)
10415 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10416 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010417 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010418 }
10419
10420 if (I == E)
10421 break;
10422
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010423 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010424 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010425 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010426 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010427 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010428
10429 ++Idx, ++I;
10430 } while (1);
10431 }
10432
Devang Patel19c87462008-09-26 22:53:05 +000010433 // Add any function attributes.
10434 if (Attributes Attr = Attrs.getFnAttributes())
10435 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10436
Duncan Sandscdb6d922007-09-17 10:26:40 +000010437 // The trampoline may have been bitcast to a bogus type (FTy).
10438 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010439 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010440
Duncan Sandscdb6d922007-09-17 10:26:40 +000010441 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010442 NewTypes.reserve(FTy->getNumParams()+1);
10443
Duncan Sandscdb6d922007-09-17 10:26:40 +000010444 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010445 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010446 {
10447 unsigned Idx = 1;
10448 FunctionType::param_iterator I = FTy->param_begin(),
10449 E = FTy->param_end();
10450
10451 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010452 if (Idx == NestIdx)
10453 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010454 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010455
10456 if (I == E)
10457 break;
10458
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010459 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010460 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010461
10462 ++Idx, ++I;
10463 } while (1);
10464 }
10465
10466 // Replace the trampoline call with a direct call. Let the generic
10467 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010468 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010469 FTy->isVarArg());
10470 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010471 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010472 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010473 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010474 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10475 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010476
10477 Instruction *NewCaller;
10478 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010479 NewCaller = InvokeInst::Create(NewCallee,
10480 II->getNormalDest(), II->getUnwindDest(),
10481 NewArgs.begin(), NewArgs.end(),
10482 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010483 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010484 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010485 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010486 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10487 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010488 if (cast<CallInst>(Caller)->isTailCall())
10489 cast<CallInst>(NewCaller)->setTailCall();
10490 cast<CallInst>(NewCaller)->
10491 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010492 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010493 }
Owen Anderson1d0be152009-08-13 21:58:54 +000010494 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010495 Caller->replaceAllUsesWith(NewCaller);
10496 Caller->eraseFromParent();
10497 RemoveFromWorkList(Caller);
10498 return 0;
10499 }
10500 }
10501
10502 // Replace the trampoline call with a direct call. Since there is no 'nest'
10503 // parameter, there is no need to adjust the argument list. Let the generic
10504 // code sort out any function type mismatches.
10505 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010506 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010507 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010508 CS.setCalledFunction(NewCallee);
10509 return CS.getInstruction();
10510}
10511
Chris Lattner7da52b22006-11-01 04:51:18 +000010512/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10513/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10514/// and a single binop.
10515Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10516 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010517 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010518 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010519 Value *LHSVal = FirstInst->getOperand(0);
10520 Value *RHSVal = FirstInst->getOperand(1);
10521
10522 const Type *LHSType = LHSVal->getType();
10523 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010524
10525 // Scan to see if all operands are the same opcode, all have one use, and all
10526 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010527 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010528 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010529 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010530 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010531 // types or GEP's with different index types.
10532 I->getOperand(0)->getType() != LHSType ||
10533 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010534 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010535
10536 // If they are CmpInst instructions, check their predicates
10537 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10538 if (cast<CmpInst>(I)->getPredicate() !=
10539 cast<CmpInst>(FirstInst)->getPredicate())
10540 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010541
10542 // Keep track of which operand needs a phi node.
10543 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10544 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010545 }
10546
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010547 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010548
Chris Lattner7da52b22006-11-01 04:51:18 +000010549 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010550 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010551 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010552 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010553 NewLHS = PHINode::Create(LHSType,
10554 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010555 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10556 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010557 InsertNewInstBefore(NewLHS, PN);
10558 LHSVal = NewLHS;
10559 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010560
10561 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010562 NewRHS = PHINode::Create(RHSType,
10563 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010564 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10565 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010566 InsertNewInstBefore(NewRHS, PN);
10567 RHSVal = NewRHS;
10568 }
10569
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010570 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010571 if (NewLHS || NewRHS) {
10572 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10573 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10574 if (NewLHS) {
10575 Value *NewInLHS = InInst->getOperand(0);
10576 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10577 }
10578 if (NewRHS) {
10579 Value *NewInRHS = InInst->getOperand(1);
10580 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10581 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010582 }
10583 }
10584
Chris Lattner7da52b22006-11-01 04:51:18 +000010585 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010586 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010587 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010588 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010589 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010590}
10591
Chris Lattner05f18922008-12-01 02:34:36 +000010592Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10593 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10594
10595 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10596 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010597 // This is true if all GEP bases are allocas and if all indices into them are
10598 // constants.
10599 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010600
10601 // Scan to see if all operands are the same opcode, all have one use, and all
10602 // kill their operands (i.e. the operands have one use).
10603 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10604 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10605 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10606 GEP->getNumOperands() != FirstInst->getNumOperands())
10607 return 0;
10608
Chris Lattner36d3e322009-02-21 00:46:50 +000010609 // Keep track of whether or not all GEPs are of alloca pointers.
10610 if (AllBasePointersAreAllocas &&
10611 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10612 !GEP->hasAllConstantIndices()))
10613 AllBasePointersAreAllocas = false;
10614
Chris Lattner05f18922008-12-01 02:34:36 +000010615 // Compare the operand lists.
10616 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10617 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10618 continue;
10619
10620 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10621 // if one of the PHIs has a constant for the index. The index may be
10622 // substantially cheaper to compute for the constants, so making it a
10623 // variable index could pessimize the path. This also handles the case
10624 // for struct indices, which must always be constant.
10625 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10626 isa<ConstantInt>(GEP->getOperand(op)))
10627 return 0;
10628
10629 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10630 return 0;
10631 FixedOperands[op] = 0; // Needs a PHI.
10632 }
10633 }
10634
Chris Lattner36d3e322009-02-21 00:46:50 +000010635 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010636 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010637 // offset calculation, but all the predecessors will have to materialize the
10638 // stack address into a register anyway. We'd actually rather *clone* the
10639 // load up into the predecessors so that we have a load of a gep of an alloca,
10640 // which can usually all be folded into the load.
10641 if (AllBasePointersAreAllocas)
10642 return 0;
10643
Chris Lattner05f18922008-12-01 02:34:36 +000010644 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10645 // that is variable.
10646 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10647
10648 bool HasAnyPHIs = false;
10649 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10650 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10651 Value *FirstOp = FirstInst->getOperand(i);
10652 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10653 FirstOp->getName()+".pn");
10654 InsertNewInstBefore(NewPN, PN);
10655
10656 NewPN->reserveOperandSpace(e);
10657 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10658 OperandPhis[i] = NewPN;
10659 FixedOperands[i] = NewPN;
10660 HasAnyPHIs = true;
10661 }
10662
10663
10664 // Add all operands to the new PHIs.
10665 if (HasAnyPHIs) {
10666 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10667 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10668 BasicBlock *InBB = PN.getIncomingBlock(i);
10669
10670 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10671 if (PHINode *OpPhi = OperandPhis[op])
10672 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10673 }
10674 }
10675
10676 Value *Base = FixedOperands[0];
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010677 GetElementPtrInst *GEP =
10678 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10679 FixedOperands.end());
10680 if (cast<GEPOperator>(FirstInst)->isInBounds())
10681 cast<GEPOperator>(GEP)->setIsInBounds(true);
10682 return GEP;
Chris Lattner05f18922008-12-01 02:34:36 +000010683}
10684
10685
Chris Lattner21550882009-02-23 05:56:17 +000010686/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10687/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010688/// obvious the value of the load is not changed from the point of the load to
10689/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010690///
10691/// Finally, it is safe, but not profitable, to sink a load targetting a
10692/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10693/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010694static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010695 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10696
10697 for (++BBI; BBI != E; ++BBI)
10698 if (BBI->mayWriteToMemory())
10699 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010700
10701 // Check for non-address taken alloca. If not address-taken already, it isn't
10702 // profitable to do this xform.
10703 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10704 bool isAddressTaken = false;
10705 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10706 UI != E; ++UI) {
10707 if (isa<LoadInst>(UI)) continue;
10708 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10709 // If storing TO the alloca, then the address isn't taken.
10710 if (SI->getOperand(1) == AI) continue;
10711 }
10712 isAddressTaken = true;
10713 break;
10714 }
10715
Chris Lattner36d3e322009-02-21 00:46:50 +000010716 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010717 return false;
10718 }
10719
Chris Lattner36d3e322009-02-21 00:46:50 +000010720 // If this load is a load from a GEP with a constant offset from an alloca,
10721 // then we don't want to sink it. In its present form, it will be
10722 // load [constant stack offset]. Sinking it will cause us to have to
10723 // materialize the stack addresses in each predecessor in a register only to
10724 // do a shared load from register in the successor.
10725 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10726 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10727 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10728 return false;
10729
Chris Lattner76c73142006-11-01 07:13:54 +000010730 return true;
10731}
10732
Chris Lattner9fe38862003-06-19 17:00:31 +000010733
Chris Lattnerbac32862004-11-14 19:13:23 +000010734// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10735// operator and they all are only used by the PHI, PHI together their
10736// inputs, and do the operation once, to the result of the PHI.
10737Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10738 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10739
10740 // Scan the instruction, looking for input operations that can be folded away.
10741 // If all input operands to the phi are the same instruction (e.g. a cast from
10742 // the same type or "+42") we can pull the operation through the PHI, reducing
10743 // code size and simplifying code.
10744 Constant *ConstantOp = 0;
10745 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010746 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010747 if (isa<CastInst>(FirstInst)) {
10748 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010749 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010750 // Can fold binop, compare or shift here if the RHS is a constant,
10751 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010752 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010753 if (ConstantOp == 0)
10754 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010755 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10756 isVolatile = LI->isVolatile();
10757 // We can't sink the load if the loaded value could be modified between the
10758 // load and the PHI.
10759 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010760 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010761 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010762
10763 // If the PHI is of volatile loads and the load block has multiple
10764 // successors, sinking it would remove a load of the volatile value from
10765 // the path through the other successor.
10766 if (isVolatile &&
10767 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10768 return 0;
10769
Chris Lattner9c080502006-11-01 07:43:41 +000010770 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010771 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010772 } else {
10773 return 0; // Cannot fold this operation.
10774 }
10775
10776 // Check to see if all arguments are the same operation.
10777 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10778 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10779 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010780 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010781 return 0;
10782 if (CastSrcTy) {
10783 if (I->getOperand(0)->getType() != CastSrcTy)
10784 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010785 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010786 // We can't sink the load if the loaded value could be modified between
10787 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010788 if (LI->isVolatile() != isVolatile ||
10789 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010790 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010791 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010792
Chris Lattner71042962008-07-08 17:18:32 +000010793 // If the PHI is of volatile loads and the load block has multiple
10794 // successors, sinking it would remove a load of the volatile value from
10795 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010796 if (isVolatile &&
10797 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10798 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010799
Chris Lattnerbac32862004-11-14 19:13:23 +000010800 } else if (I->getOperand(1) != ConstantOp) {
10801 return 0;
10802 }
10803 }
10804
10805 // Okay, they are all the same operation. Create a new PHI node of the
10806 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010807 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10808 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010809 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010810
10811 Value *InVal = FirstInst->getOperand(0);
10812 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010813
10814 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010815 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10816 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10817 if (NewInVal != InVal)
10818 InVal = 0;
10819 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10820 }
10821
10822 Value *PhiVal;
10823 if (InVal) {
10824 // The new PHI unions all of the same values together. This is really
10825 // common, so we handle it intelligently here for compile-time speed.
10826 PhiVal = InVal;
10827 delete NewPN;
10828 } else {
10829 InsertNewInstBefore(NewPN, PN);
10830 PhiVal = NewPN;
10831 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010832
Chris Lattnerbac32862004-11-14 19:13:23 +000010833 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010834 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010835 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010836 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010837 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010838 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010839 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010840 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010841 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10842
10843 // If this was a volatile load that we are merging, make sure to loop through
10844 // and mark all the input loads as non-volatile. If we don't do this, we will
10845 // insert a new volatile load and the old ones will not be deletable.
10846 if (isVolatile)
10847 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10848 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10849
10850 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010851}
Chris Lattnera1be5662002-05-02 17:06:02 +000010852
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010853/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10854/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010855static bool DeadPHICycle(PHINode *PN,
10856 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010857 if (PN->use_empty()) return true;
10858 if (!PN->hasOneUse()) return false;
10859
10860 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010861 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010862 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010863
10864 // Don't scan crazily complex things.
10865 if (PotentiallyDeadPHIs.size() == 16)
10866 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010867
10868 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10869 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010870
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010871 return false;
10872}
10873
Chris Lattnercf5008a2007-11-06 21:52:06 +000010874/// PHIsEqualValue - Return true if this phi node is always equal to
10875/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10876/// z = some value; x = phi (y, z); y = phi (x, z)
10877static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10878 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10879 // See if we already saw this PHI node.
10880 if (!ValueEqualPHIs.insert(PN))
10881 return true;
10882
10883 // Don't scan crazily complex things.
10884 if (ValueEqualPHIs.size() == 16)
10885 return false;
10886
10887 // Scan the operands to see if they are either phi nodes or are equal to
10888 // the value.
10889 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10890 Value *Op = PN->getIncomingValue(i);
10891 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10892 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10893 return false;
10894 } else if (Op != NonPhiInVal)
10895 return false;
10896 }
10897
10898 return true;
10899}
10900
10901
Chris Lattner473945d2002-05-06 18:06:38 +000010902// PHINode simplification
10903//
Chris Lattner7e708292002-06-25 16:13:24 +000010904Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010905 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010906 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010907
Owen Anderson7e057142006-07-10 22:03:18 +000010908 if (Value *V = PN.hasConstantValue())
10909 return ReplaceInstUsesWith(PN, V);
10910
Owen Anderson7e057142006-07-10 22:03:18 +000010911 // If all PHI operands are the same operation, pull them through the PHI,
10912 // reducing code size.
10913 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010914 isa<Instruction>(PN.getIncomingValue(1)) &&
10915 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10916 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10917 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10918 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010919 PN.getIncomingValue(0)->hasOneUse())
10920 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10921 return Result;
10922
10923 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10924 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10925 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010926 if (PN.hasOneUse()) {
10927 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10928 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010929 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010930 PotentiallyDeadPHIs.insert(&PN);
10931 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010932 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010933 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010934
10935 // If this phi has a single use, and if that use just computes a value for
10936 // the next iteration of a loop, delete the phi. This occurs with unused
10937 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10938 // common case here is good because the only other things that catch this
10939 // are induction variable analysis (sometimes) and ADCE, which is only run
10940 // late.
10941 if (PHIUser->hasOneUse() &&
10942 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10943 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010944 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010945 }
10946 }
Owen Anderson7e057142006-07-10 22:03:18 +000010947
Chris Lattnercf5008a2007-11-06 21:52:06 +000010948 // We sometimes end up with phi cycles that non-obviously end up being the
10949 // same value, for example:
10950 // z = some value; x = phi (y, z); y = phi (x, z)
10951 // where the phi nodes don't necessarily need to be in the same block. Do a
10952 // quick check to see if the PHI node only contains a single non-phi value, if
10953 // so, scan to see if the phi cycle is actually equal to that value.
10954 {
10955 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10956 // Scan for the first non-phi operand.
10957 while (InValNo != NumOperandVals &&
10958 isa<PHINode>(PN.getIncomingValue(InValNo)))
10959 ++InValNo;
10960
10961 if (InValNo != NumOperandVals) {
10962 Value *NonPhiInVal = PN.getOperand(InValNo);
10963
10964 // Scan the rest of the operands to see if there are any conflicts, if so
10965 // there is no need to recursively scan other phis.
10966 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10967 Value *OpVal = PN.getIncomingValue(InValNo);
10968 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10969 break;
10970 }
10971
10972 // If we scanned over all operands, then we have one unique value plus
10973 // phi values. Scan PHI nodes to see if they all merge in each other or
10974 // the value.
10975 if (InValNo == NumOperandVals) {
10976 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10977 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10978 return ReplaceInstUsesWith(PN, NonPhiInVal);
10979 }
10980 }
10981 }
Chris Lattner60921c92003-12-19 05:58:40 +000010982 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010983}
10984
Reid Spencer17212df2006-12-12 09:18:51 +000010985static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10986 Instruction *InsertPoint,
10987 InstCombiner *IC) {
Dan Gohman6de29f82009-06-15 22:12:54 +000010988 unsigned PtrSize = DTy->getScalarSizeInBits();
10989 unsigned VTySize = V->getType()->getScalarSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010990 // We must cast correctly to the pointer type. Ensure that we
10991 // sign extend the integer value if it is smaller as this is
10992 // used for address computation.
10993 Instruction::CastOps opcode =
10994 (VTySize < PtrSize ? Instruction::SExt :
10995 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10996 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010997}
10998
Chris Lattnera1be5662002-05-02 17:06:02 +000010999
Chris Lattner7e708292002-06-25 16:13:24 +000011000Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000011001 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000011002 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000011003 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011004 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000011005 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011006
Chris Lattnere87597f2004-10-16 18:11:37 +000011007 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011008 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011009
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011010 bool HasZeroPointerIndex = false;
11011 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11012 HasZeroPointerIndex = C->isNullValue();
11013
11014 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011015 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011016
Chris Lattner28977af2004-04-05 01:30:19 +000011017 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000011018 if (TD) {
11019 bool MadeChange = false;
11020 unsigned PtrSize = TD->getPointerSizeInBits();
11021
11022 gep_type_iterator GTI = gep_type_begin(GEP);
11023 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11024 I != E; ++I, ++GTI) {
11025 if (!isa<SequentialType>(*GTI)) continue;
11026
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011027 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000011028 // to what we need. If narrower, sign-extend it to what we need. This
11029 // explicit cast can make subsequent optimizations more obvious.
11030 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
11031
11032 if (OpBits == PtrSize)
11033 continue;
11034
11035 Instruction::CastOps Opc =
11036 OpBits > PtrSize ? Instruction::Trunc : Instruction::SExt;
11037 *I = InsertCastBefore(Opc, *I, TD->getIntPtrType(GEP.getContext()), GEP);
11038 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000011039 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000011040 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011041 }
Chris Lattner28977af2004-04-05 01:30:19 +000011042
Chris Lattner90ac28c2002-08-02 19:29:35 +000011043 // Combine Indices - If the source pointer to this getelementptr instruction
11044 // is a getelementptr instruction, combine the indices of the two
11045 // getelementptr instructions into a single instruction.
11046 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011047 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000011048 // Note that if our source is a gep chain itself that we wait for that
11049 // chain to be resolved before we perform this transformation. This
11050 // avoids us creating a TON of code in some cases.
11051 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011052 if (GetElementPtrInst *SrcGEP =
11053 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11054 if (SrcGEP->getNumOperands() == 2)
11055 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000011056
Chris Lattner72588fc2007-02-15 22:48:32 +000011057 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011058
11059 // Find out whether the last index in the source GEP is a sequential idx.
11060 bool EndsWithSequential = false;
11061 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11062 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011063 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011064
Chris Lattner90ac28c2002-08-02 19:29:35 +000011065 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011066 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011067 // Replace: gep (gep %P, long B), long A, ...
11068 // With: T = long A+B; gep %P, T, ...
11069 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011070 Value *Sum;
11071 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11072 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000011073 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011074 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000011075 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011076 Sum = SO1;
11077 } else {
11078 // If they aren't the same type, convert both to an integer of the
11079 // target's pointer size.
11080 if (SO1->getType() != GO1->getType()) {
11081 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011082 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011083 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011084 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011085 } else if (TD) {
Duncan Sands514ab342007-11-01 20:53:16 +000011086 unsigned PS = TD->getPointerSizeInBits();
11087 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011088 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011089 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Duncan Sands514ab342007-11-01 20:53:16 +000011090 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011091 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011092 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011093 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000011094 const Type *PT = TD->getIntPtrType(GEP.getContext());
Reid Spencer17212df2006-12-12 09:18:51 +000011095 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11096 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011097 }
11098 }
11099 }
Chris Lattner620ce142004-05-07 22:09:22 +000011100 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Chris Lattnerccf4b342009-08-30 04:49:01 +000011101 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
Chris Lattner620ce142004-05-07 22:09:22 +000011102 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011103 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011104 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011105 }
Chris Lattner28977af2004-04-05 01:30:19 +000011106 }
Chris Lattner620ce142004-05-07 22:09:22 +000011107
11108 // Recycle the GEP we already have if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011109 if (Src->getNumOperands() == 2) {
11110 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000011111 GEP.setOperand(1, Sum);
11112 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000011113 }
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011114 Indices.insert(Indices.end(), Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011115 Indices.push_back(Sum);
11116 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000011117 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011118 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011119 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011120 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011121 Indices.insert(Indices.end(), Src->op_begin()+1, Src->op_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011122 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11123 }
11124
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011125 if (!Indices.empty()) {
Chris Lattnerccf4b342009-08-30 04:49:01 +000011126 GetElementPtrInst *NewGEP =
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011127 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000011128 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000011129 if (cast<GEPOperator>(&GEP)->isInBounds() && Src->isInBounds())
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011130 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11131 return NewGEP;
11132 }
Chris Lattner6e24d832009-08-30 05:00:50 +000011133 }
11134
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011135 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11136 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011137 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
11138
11139 if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011140 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11141 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011142 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011143 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11144 // into : GEP i8* X, ...
11145 //
Chris Lattnereed48272005-09-13 00:40:14 +000011146 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011147 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11148 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011149 if (const ArrayType *CATy =
11150 dyn_cast<ArrayType>(CPTy->getElementType())) {
11151 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11152 if (CATy->getElementType() == XTy->getElementType()) {
11153 // -> GEP i8* X, ...
11154 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011155 GetElementPtrInst *NewGEP =
11156 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11157 GEP.getName());
11158 if (cast<GEPOperator>(&GEP)->isInBounds())
11159 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11160 return NewGEP;
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011161 } else if (const ArrayType *XATy =
11162 dyn_cast<ArrayType>(XTy->getElementType())) {
11163 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011164 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011165 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011166 // At this point, we know that the cast source type is a pointer
11167 // to an array of the same type as the destination pointer
11168 // array. Because the array type is never stepped over (there
11169 // is a leading zero) we can fold the cast into this GEP.
11170 GEP.setOperand(0, X);
11171 return &GEP;
11172 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011173 }
11174 }
Chris Lattnereed48272005-09-13 00:40:14 +000011175 } else if (GEP.getNumOperands() == 2) {
11176 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011177 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11178 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011179 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11180 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011181 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011182 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11183 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011184 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011185 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011186 Idx[1] = GEP.getOperand(1);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011187 GetElementPtrInst *NewGEP =
11188 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11189 if (cast<GEPOperator>(&GEP)->isInBounds())
11190 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11191 Value *V = InsertNewInstBefore(NewGEP, GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011192 // V and GEP are both pointer types --> BitCast
11193 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011194 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011195
11196 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011197 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011198 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011199 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011200
Owen Anderson1d0be152009-08-13 21:58:54 +000011201 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011202 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011203 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011204
11205 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11206 // allow either a mul, shift, or constant here.
11207 Value *NewIdx = 0;
11208 ConstantInt *Scale = 0;
11209 if (ArrayEltSize == 1) {
11210 NewIdx = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011211 Scale =
Owen Andersoneed707b2009-07-24 23:12:02 +000011212 ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011213 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011214 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011215 Scale = CI;
11216 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11217 if (Inst->getOpcode() == Instruction::Shl &&
11218 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011219 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11220 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011221 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011222 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011223 NewIdx = Inst->getOperand(0);
11224 } else if (Inst->getOpcode() == Instruction::Mul &&
11225 isa<ConstantInt>(Inst->getOperand(1))) {
11226 Scale = cast<ConstantInt>(Inst->getOperand(1));
11227 NewIdx = Inst->getOperand(0);
11228 }
11229 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011230
Chris Lattner7835cdd2005-09-13 18:36:04 +000011231 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011232 // out, perform the transformation. Note, we don't know whether Scale is
11233 // signed or not. We'll use unsigned version of division/modulo
11234 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011235 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011236 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011237 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011238 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011239 if (Scale->getZExtValue() != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011240 Constant *C =
Owen Andersonbaf3c402009-07-29 18:55:55 +000011241 ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011242 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011243 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011244 NewIdx = InsertNewInstBefore(Sc, GEP);
11245 }
11246
11247 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011248 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011249 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011250 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011251 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011252 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011253 if (cast<GEPOperator>(&GEP)->isInBounds())
11254 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
Reid Spencer3da59db2006-11-27 01:05:10 +000011255 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11256 // The NewGEP must be pointer typed, so must the old one -> BitCast
11257 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011258 }
11259 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011260 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011261 }
Chris Lattner58407792009-01-09 04:53:57 +000011262
Chris Lattner46cd5a12009-01-09 05:44:56 +000011263 /// See if we can simplify:
11264 /// X = bitcast A to B*
11265 /// Y = gep X, <...constant indices...>
11266 /// into a gep of the original struct. This is important for SROA and alias
11267 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011268 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011269 if (TD &&
11270 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011271 // Determine how much the GEP moves the pointer. We are guaranteed to get
11272 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011273 ConstantInt *OffsetV =
11274 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011275 int64_t Offset = OffsetV->getSExtValue();
11276
11277 // If this GEP instruction doesn't move the pointer, just replace the GEP
11278 // with a bitcast of the real input to the dest type.
11279 if (Offset == 0) {
11280 // If the bitcast is of an allocation, and the allocation will be
11281 // converted to match the type of the cast, don't touch this.
11282 if (isa<AllocationInst>(BCI->getOperand(0))) {
11283 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11284 if (Instruction *I = visitBitCast(*BCI)) {
11285 if (I != BCI) {
11286 I->takeName(BCI);
11287 BCI->getParent()->getInstList().insert(BCI, I);
11288 ReplaceInstUsesWith(*BCI, I);
11289 }
11290 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011291 }
Chris Lattner58407792009-01-09 04:53:57 +000011292 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011293 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011294 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011295
11296 // Otherwise, if the offset is non-zero, we need to find out if there is a
11297 // field at Offset in 'A's type. If so, we can pull the cast through the
11298 // GEP.
11299 SmallVector<Value*, 8> NewIndices;
11300 const Type *InTy =
11301 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011302 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011303 Instruction *NGEP =
11304 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11305 NewIndices.end());
11306 if (NGEP->getType() == GEP.getType()) return NGEP;
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011307 if (cast<GEPOperator>(&GEP)->isInBounds())
11308 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011309 InsertNewInstBefore(NGEP, GEP);
11310 NGEP->takeName(&GEP);
11311 return new BitCastInst(NGEP, GEP.getType());
11312 }
Chris Lattner58407792009-01-09 04:53:57 +000011313 }
11314 }
11315
Chris Lattner8a2a3112001-12-14 16:52:21 +000011316 return 0;
11317}
11318
Chris Lattner0864acf2002-11-04 16:18:53 +000011319Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11320 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011321 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011322 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11323 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011324 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011325 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011326
11327 // Create and insert the replacement instruction...
11328 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +000011329 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011330 else {
11331 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Owen Anderson50dead02009-07-15 23:53:25 +000011332 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011333 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011334
11335 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011336
Chris Lattner0864acf2002-11-04 16:18:53 +000011337 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011338 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011339 //
11340 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011341 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011342
11343 // Now that I is pointing to the first non-allocation-inst in the block,
11344 // insert our getelementptr instruction...
11345 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011346 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011347 Value *Idx[2];
11348 Idx[0] = NullIdx;
11349 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011350 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11351 New->getName()+".sub", It);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011352 cast<GEPOperator>(V)->setIsInBounds(true);
Chris Lattner0864acf2002-11-04 16:18:53 +000011353
11354 // Now make everything use the getelementptr instead of the original
11355 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011356 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011357 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011358 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011359 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011360 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011361
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011362 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011363 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011364 // Note that we only do this for alloca's, because malloc should allocate
11365 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011366 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011367 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011368
11369 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11370 if (AI.getAlignment() == 0)
11371 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11372 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011373
Chris Lattner0864acf2002-11-04 16:18:53 +000011374 return 0;
11375}
11376
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011377Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11378 Value *Op = FI.getOperand(0);
11379
Chris Lattner17be6352004-10-18 02:59:09 +000011380 // free undef -> unreachable.
11381 if (isa<UndefValue>(Op)) {
11382 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011383 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +000011384 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011385 return EraseInstFromFunction(FI);
11386 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011387
Chris Lattner6160e852004-02-28 04:57:37 +000011388 // If we have 'free null' delete the instruction. This can happen in stl code
11389 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011390 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011391 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011392
11393 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11394 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11395 FI.setOperand(0, CI->getOperand(0));
11396 return &FI;
11397 }
11398
11399 // Change free (gep X, 0,0,0,0) into free(X)
11400 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11401 if (GEPI->hasAllZeroIndices()) {
11402 AddToWorkList(GEPI);
11403 FI.setOperand(0, GEPI->getOperand(0));
11404 return &FI;
11405 }
11406 }
11407
11408 // Change free(malloc) into nothing, if the malloc has a single use.
11409 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11410 if (MI->hasOneUse()) {
11411 EraseInstFromFunction(FI);
11412 return EraseInstFromFunction(*MI);
11413 }
Chris Lattner6160e852004-02-28 04:57:37 +000011414
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011415 return 0;
11416}
11417
11418
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011419/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011420static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011421 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011422 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011423 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011424 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011425
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011426 if (TD) {
11427 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11428 // Instead of loading constant c string, use corresponding integer value
11429 // directly if string length is small enough.
11430 std::string Str;
11431 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11432 unsigned len = Str.length();
11433 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11434 unsigned numBits = Ty->getPrimitiveSizeInBits();
11435 // Replace LI with immediate integer store.
11436 if ((numBits >> 3) == len + 1) {
11437 APInt StrVal(numBits, 0);
11438 APInt SingleChar(numBits, 0);
11439 if (TD->isLittleEndian()) {
11440 for (signed i = len-1; i >= 0; i--) {
11441 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11442 StrVal = (StrVal << 8) | SingleChar;
11443 }
11444 } else {
11445 for (unsigned i = 0; i < len; i++) {
11446 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11447 StrVal = (StrVal << 8) | SingleChar;
11448 }
11449 // Append NULL at the end.
11450 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011451 StrVal = (StrVal << 8) | SingleChar;
11452 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011453 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011454 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011455 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011456 }
11457 }
11458 }
11459
Mon P Wang6753f952009-02-07 22:19:29 +000011460 const PointerType *DestTy = cast<PointerType>(CI->getType());
11461 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011462 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011463
11464 // If the address spaces don't match, don't eliminate the cast.
11465 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11466 return 0;
11467
Chris Lattnerb89e0712004-07-13 01:49:43 +000011468 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011469
Reid Spencer42230162007-01-22 05:51:25 +000011470 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011471 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011472 // If the source is an array, the code below will not succeed. Check to
11473 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11474 // constants.
11475 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11476 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11477 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011478 Value *Idxs[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011479 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +000011480 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011481 SrcTy = cast<PointerType>(CastOp->getType());
11482 SrcPTy = SrcTy->getElementType();
11483 }
11484
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011485 if (IC.getTargetData() &&
11486 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011487 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011488 // Do not allow turning this into a load of an integer, which is then
11489 // casted to a pointer, this pessimizes pointer analysis a lot.
11490 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011491 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11492 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011493
Chris Lattnerf9527852005-01-31 04:50:46 +000011494 // Okay, we are casting from one integer or pointer type to another of
11495 // the same size. Instead of casting the pointer before the load, cast
11496 // the result of the loaded value.
11497 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11498 CI->getName(),
11499 LI.isVolatile()),LI);
11500 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011501 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011502 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011503 }
11504 }
11505 return 0;
11506}
11507
Chris Lattner833b8a42003-06-26 05:06:25 +000011508Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11509 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011510
Dan Gohman9941f742007-07-20 16:34:21 +000011511 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011512 if (TD) {
11513 unsigned KnownAlign =
11514 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11515 if (KnownAlign >
11516 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11517 LI.getAlignment()))
11518 LI.setAlignment(KnownAlign);
11519 }
Dan Gohman9941f742007-07-20 16:34:21 +000011520
Chris Lattner37366c12005-05-01 04:24:53 +000011521 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011522 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011523 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011524 return Res;
11525
11526 // None of the following transforms are legal for volatile loads.
11527 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011528
Dan Gohman2276a7b2008-10-15 23:19:35 +000011529 // Do really simple store-to-load forwarding and load CSE, to catch cases
11530 // where there are several consequtive memory accesses to the same location,
11531 // separated by a few arithmetic operations.
11532 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011533 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11534 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011535
Christopher Lambb15147e2007-12-29 07:56:53 +000011536 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11537 const Value *GEPI0 = GEPI->getOperand(0);
11538 // TODO: Consider a target hook for valid address spaces for this xform.
11539 if (isa<ConstantPointerNull>(GEPI0) &&
11540 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011541 // Insert a new store to null instruction before the load to indicate
11542 // that this code is not reachable. We do this instead of inserting
11543 // an unreachable instruction directly because we cannot modify the
11544 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011545 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011546 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011547 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011548 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011549 }
Chris Lattner37366c12005-05-01 04:24:53 +000011550
Chris Lattnere87597f2004-10-16 18:11:37 +000011551 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011552 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011553 // TODO: Consider a target hook for valid address spaces for this xform.
11554 if (isa<UndefValue>(C) || (C->isNullValue() &&
11555 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011556 // Insert a new store to null instruction before the load to indicate that
11557 // this code is not reachable. We do this instead of inserting an
11558 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011559 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011560 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011561 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011562 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011563
Chris Lattnere87597f2004-10-16 18:11:37 +000011564 // Instcombine load (constant global) into the value loaded.
11565 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011566 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011567 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011568
Chris Lattnere87597f2004-10-16 18:11:37 +000011569 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011570 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011571 if (CE->getOpcode() == Instruction::GetElementPtr) {
11572 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011573 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011574 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011575 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Andersone922c022009-07-22 00:24:57 +000011576 *Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011577 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011578 if (CE->getOperand(0)->isNullValue()) {
11579 // Insert a new store to null instruction before the load to indicate
11580 // that this code is not reachable. We do this instead of inserting
11581 // an unreachable instruction directly because we cannot modify the
11582 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011583 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011584 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011585 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011586 }
11587
Reid Spencer3da59db2006-11-27 01:05:10 +000011588 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011589 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011590 return Res;
11591 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011592 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011593 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011594
11595 // If this load comes from anywhere in a constant global, and if the global
11596 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011597 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011598 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011599 if (GV->getInitializer()->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +000011600 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011601 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011602 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011603 }
11604 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011605
Chris Lattner37366c12005-05-01 04:24:53 +000011606 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011607 // Change select and PHI nodes to select values instead of addresses: this
11608 // helps alias analysis out a lot, allows many others simplifications, and
11609 // exposes redundancy in the code.
11610 //
11611 // Note that we cannot do the transformation unless we know that the
11612 // introduced loads cannot trap! Something like this is valid as long as
11613 // the condition is always false: load (select bool %C, int* null, int* %G),
11614 // but it would not be valid if we transformed it to load from null
11615 // unconditionally.
11616 //
11617 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11618 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011619 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11620 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011621 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011622 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011623 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011624 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011625 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011626 }
11627
Chris Lattner684fe212004-09-23 15:46:00 +000011628 // load (select (cond, null, P)) -> load P
11629 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11630 if (C->isNullValue()) {
11631 LI.setOperand(0, SI->getOperand(2));
11632 return &LI;
11633 }
11634
11635 // load (select (cond, P, null)) -> load P
11636 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11637 if (C->isNullValue()) {
11638 LI.setOperand(0, SI->getOperand(1));
11639 return &LI;
11640 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011641 }
11642 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011643 return 0;
11644}
11645
Reid Spencer55af2b52007-01-19 21:20:31 +000011646/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011647/// when possible. This makes it generally easy to do alias analysis and/or
11648/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011649static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11650 User *CI = cast<User>(SI.getOperand(1));
11651 Value *CastOp = CI->getOperand(0);
11652
11653 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011654 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11655 if (SrcTy == 0) return 0;
11656
11657 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011658
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011659 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11660 return 0;
11661
Chris Lattner3914f722009-01-24 01:00:13 +000011662 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11663 /// to its first element. This allows us to handle things like:
11664 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11665 /// on 32-bit hosts.
11666 SmallVector<Value*, 4> NewGEPIndices;
11667
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011668 // If the source is an array, the code below will not succeed. Check to
11669 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11670 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011671 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11672 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011673 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011674 NewGEPIndices.push_back(Zero);
11675
11676 while (1) {
11677 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011678 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011679 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011680 NewGEPIndices.push_back(Zero);
11681 SrcPTy = STy->getElementType(0);
11682 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11683 NewGEPIndices.push_back(Zero);
11684 SrcPTy = ATy->getElementType();
11685 } else {
11686 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011687 }
Chris Lattner3914f722009-01-24 01:00:13 +000011688 }
11689
Owen Andersondebcb012009-07-29 22:17:13 +000011690 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011691 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011692
11693 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11694 return 0;
11695
Chris Lattner71759c42009-01-16 20:12:52 +000011696 // If the pointers point into different address spaces or if they point to
11697 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011698 if (!IC.getTargetData() ||
11699 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011700 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011701 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11702 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011703 return 0;
11704
11705 // Okay, we are casting from one integer or pointer type to another of
11706 // the same size. Instead of casting the pointer before
11707 // the store, cast the value to be stored.
11708 Value *NewCast;
11709 Value *SIOp0 = SI.getOperand(0);
11710 Instruction::CastOps opcode = Instruction::BitCast;
11711 const Type* CastSrcTy = SIOp0->getType();
11712 const Type* CastDstTy = SrcPTy;
11713 if (isa<PointerType>(CastDstTy)) {
11714 if (CastSrcTy->isInteger())
11715 opcode = Instruction::IntToPtr;
11716 } else if (isa<IntegerType>(CastDstTy)) {
11717 if (isa<PointerType>(SIOp0->getType()))
11718 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011719 }
Chris Lattner3914f722009-01-24 01:00:13 +000011720
11721 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11722 // emit a GEP to index into its first field.
11723 if (!NewGEPIndices.empty()) {
11724 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Andersonbaf3c402009-07-29 18:55:55 +000011725 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner3914f722009-01-24 01:00:13 +000011726 NewGEPIndices.size());
11727 else
11728 CastOp = IC.InsertNewInstBefore(
11729 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11730 NewGEPIndices.end()), SI);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011731 cast<GEPOperator>(CastOp)->setIsInBounds(true);
Chris Lattner3914f722009-01-24 01:00:13 +000011732 }
11733
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011734 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Andersonbaf3c402009-07-29 18:55:55 +000011735 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011736 else
11737 NewCast = IC.InsertNewInstBefore(
11738 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11739 SI);
11740 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011741}
11742
Chris Lattner4aebaee2008-11-27 08:56:30 +000011743/// equivalentAddressValues - Test if A and B will obviously have the same
11744/// value. This includes recognizing that %t0 and %t1 will have the same
11745/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011746/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011747/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011748/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011749/// %t2 = load i32* %t1
11750///
11751static bool equivalentAddressValues(Value *A, Value *B) {
11752 // Test if the values are trivially equivalent.
11753 if (A == B) return true;
11754
11755 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011756 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11757 // its only used to compare two uses within the same basic block, which
11758 // means that they'll always either have the same value or one of them
11759 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011760 if (isa<BinaryOperator>(A) ||
11761 isa<CastInst>(A) ||
11762 isa<PHINode>(A) ||
11763 isa<GetElementPtrInst>(A))
11764 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011765 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011766 return true;
11767
11768 // Otherwise they may not be equivalent.
11769 return false;
11770}
11771
Dale Johannesen4945c652009-03-03 21:26:39 +000011772// If this instruction has two uses, one of which is a llvm.dbg.declare,
11773// return the llvm.dbg.declare.
11774DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11775 if (!V->hasNUses(2))
11776 return 0;
11777 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11778 UI != E; ++UI) {
11779 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11780 return DI;
11781 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11782 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11783 return DI;
11784 }
11785 }
11786 return 0;
11787}
11788
Chris Lattner2f503e62005-01-31 05:36:43 +000011789Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11790 Value *Val = SI.getOperand(0);
11791 Value *Ptr = SI.getOperand(1);
11792
11793 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011794 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011795 ++NumCombined;
11796 return 0;
11797 }
Chris Lattner836692d2007-01-15 06:51:56 +000011798
11799 // If the RHS is an alloca with a single use, zapify the store, making the
11800 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011801 // If the RHS is an alloca with a two uses, the other one being a
11802 // llvm.dbg.declare, zapify the store and the declare, making the
11803 // alloca dead. We must do this to prevent declare's from affecting
11804 // codegen.
11805 if (!SI.isVolatile()) {
11806 if (Ptr->hasOneUse()) {
11807 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011808 EraseInstFromFunction(SI);
11809 ++NumCombined;
11810 return 0;
11811 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011812 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11813 if (isa<AllocaInst>(GEP->getOperand(0))) {
11814 if (GEP->getOperand(0)->hasOneUse()) {
11815 EraseInstFromFunction(SI);
11816 ++NumCombined;
11817 return 0;
11818 }
11819 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11820 EraseInstFromFunction(*DI);
11821 EraseInstFromFunction(SI);
11822 ++NumCombined;
11823 return 0;
11824 }
11825 }
11826 }
11827 }
11828 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11829 EraseInstFromFunction(*DI);
11830 EraseInstFromFunction(SI);
11831 ++NumCombined;
11832 return 0;
11833 }
Chris Lattner836692d2007-01-15 06:51:56 +000011834 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011835
Dan Gohman9941f742007-07-20 16:34:21 +000011836 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011837 if (TD) {
11838 unsigned KnownAlign =
11839 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11840 if (KnownAlign >
11841 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11842 SI.getAlignment()))
11843 SI.setAlignment(KnownAlign);
11844 }
Dan Gohman9941f742007-07-20 16:34:21 +000011845
Dale Johannesenacb51a32009-03-03 01:43:03 +000011846 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011847 // stores to the same location, separated by a few arithmetic operations. This
11848 // situation often occurs with bitfield accesses.
11849 BasicBlock::iterator BBI = &SI;
11850 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11851 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011852 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011853 // Don't count debug info directives, lest they affect codegen,
11854 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11855 // It is necessary for correctness to skip those that feed into a
11856 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011857 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011858 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011859 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011860 continue;
11861 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011862
11863 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11864 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011865 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11866 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011867 ++NumDeadStore;
11868 ++BBI;
11869 EraseInstFromFunction(*PrevSI);
11870 continue;
11871 }
11872 break;
11873 }
11874
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011875 // If this is a load, we have to stop. However, if the loaded value is from
11876 // the pointer we're loading and is producing the pointer we're storing,
11877 // then *this* store is dead (X = load P; store X -> P).
11878 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011879 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11880 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011881 EraseInstFromFunction(SI);
11882 ++NumCombined;
11883 return 0;
11884 }
11885 // Otherwise, this is a load from some other location. Stores before it
11886 // may not be dead.
11887 break;
11888 }
11889
Chris Lattner9ca96412006-02-08 03:25:32 +000011890 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011891 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011892 break;
11893 }
11894
11895
11896 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011897
11898 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011899 if (isa<ConstantPointerNull>(Ptr) &&
11900 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011901 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011902 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011903 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011904 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011905 ++NumCombined;
11906 }
11907 return 0; // Do not modify these!
11908 }
11909
11910 // store undef, Ptr -> noop
11911 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011912 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011913 ++NumCombined;
11914 return 0;
11915 }
11916
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011917 // If the pointer destination is a cast, see if we can fold the cast into the
11918 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011919 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011920 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11921 return Res;
11922 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011923 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011924 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11925 return Res;
11926
Chris Lattner408902b2005-09-12 23:23:25 +000011927
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011928 // If this store is the last instruction in the basic block (possibly
11929 // excepting debug info instructions and the pointer bitcasts that feed
11930 // into them), and if the block ends with an unconditional branch, try
11931 // to move it to the successor block.
11932 BBI = &SI;
11933 do {
11934 ++BBI;
11935 } while (isa<DbgInfoIntrinsic>(BBI) ||
11936 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011937 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011938 if (BI->isUnconditional())
11939 if (SimplifyStoreAtEndOfBlock(SI))
11940 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011941
Chris Lattner2f503e62005-01-31 05:36:43 +000011942 return 0;
11943}
11944
Chris Lattner3284d1f2007-04-15 00:07:55 +000011945/// SimplifyStoreAtEndOfBlock - Turn things like:
11946/// if () { *P = v1; } else { *P = v2 }
11947/// into a phi node with a store in the successor.
11948///
Chris Lattner31755a02007-04-15 01:02:18 +000011949/// Simplify things like:
11950/// *P = v1; if () { *P = v2; }
11951/// into a phi node with a store in the successor.
11952///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011953bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11954 BasicBlock *StoreBB = SI.getParent();
11955
11956 // Check to see if the successor block has exactly two incoming edges. If
11957 // so, see if the other predecessor contains a store to the same location.
11958 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011959 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011960
11961 // Determine whether Dest has exactly two predecessors and, if so, compute
11962 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011963 pred_iterator PI = pred_begin(DestBB);
11964 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011965 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011966 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011967 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011968 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011969 return false;
11970
11971 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011972 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011973 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011974 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011975 }
Chris Lattner31755a02007-04-15 01:02:18 +000011976 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011977 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011978
11979 // Bail out if all the relevant blocks aren't distinct (this can happen,
11980 // for example, if SI is in an infinite loop)
11981 if (StoreBB == DestBB || OtherBB == DestBB)
11982 return false;
11983
Chris Lattner31755a02007-04-15 01:02:18 +000011984 // Verify that the other block ends in a branch and is not otherwise empty.
11985 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011986 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011987 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011988 return false;
11989
Chris Lattner31755a02007-04-15 01:02:18 +000011990 // If the other block ends in an unconditional branch, check for the 'if then
11991 // else' case. there is an instruction before the branch.
11992 StoreInst *OtherStore = 0;
11993 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011994 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011995 // Skip over debugging info.
11996 while (isa<DbgInfoIntrinsic>(BBI) ||
11997 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11998 if (BBI==OtherBB->begin())
11999 return false;
12000 --BBI;
12001 }
12002 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012003 OtherStore = dyn_cast<StoreInst>(BBI);
12004 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12005 return false;
12006 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012007 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012008 // destinations is StoreBB, then we have the if/then case.
12009 if (OtherBr->getSuccessor(0) != StoreBB &&
12010 OtherBr->getSuccessor(1) != StoreBB)
12011 return false;
12012
12013 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012014 // if/then triangle. See if there is a store to the same ptr as SI that
12015 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012016 for (;; --BBI) {
12017 // Check to see if we find the matching store.
12018 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12019 if (OtherStore->getOperand(1) != SI.getOperand(1))
12020 return false;
12021 break;
12022 }
Eli Friedman6903a242008-06-13 22:02:12 +000012023 // If we find something that may be using or overwriting the stored
12024 // value, or if we run out of instructions, we can't do the xform.
12025 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012026 BBI == OtherBB->begin())
12027 return false;
12028 }
12029
12030 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012031 // make sure nothing reads or overwrites the stored value in
12032 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012033 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12034 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012035 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012036 return false;
12037 }
12038 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012039
Chris Lattner31755a02007-04-15 01:02:18 +000012040 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012041 Value *MergedVal = OtherStore->getOperand(0);
12042 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012043 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012044 PN->reserveOperandSpace(2);
12045 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012046 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12047 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012048 }
12049
12050 // Advance to a place where it is safe to insert the new store and
12051 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012052 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012053 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12054 OtherStore->isVolatile()), *BBI);
12055
12056 // Nuke the old stores.
12057 EraseInstFromFunction(SI);
12058 EraseInstFromFunction(*OtherStore);
12059 ++NumCombined;
12060 return true;
12061}
12062
Chris Lattner2f503e62005-01-31 05:36:43 +000012063
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012064Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12065 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012066 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012067 BasicBlock *TrueDest;
12068 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000012069 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012070 !isa<Constant>(X)) {
12071 // Swap Destinations and condition...
12072 BI.setCondition(X);
12073 BI.setSuccessor(0, FalseDest);
12074 BI.setSuccessor(1, TrueDest);
12075 return &BI;
12076 }
12077
Reid Spencere4d87aa2006-12-23 06:05:41 +000012078 // Cannonicalize fcmp_one -> fcmp_oeq
12079 FCmpInst::Predicate FPred; Value *Y;
12080 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Dan Gohman4ae51262009-08-12 16:23:25 +000012081 TrueDest, FalseDest)))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012082 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12083 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12084 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012085 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012086 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012087 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012088 // Swap Destinations and condition...
12089 BI.setCondition(NewSCC);
12090 BI.setSuccessor(0, FalseDest);
12091 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012092 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012093 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012094 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012095 return &BI;
12096 }
12097
12098 // Cannonicalize icmp_ne -> icmp_eq
12099 ICmpInst::Predicate IPred;
12100 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Dan Gohman4ae51262009-08-12 16:23:25 +000012101 TrueDest, FalseDest)))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012102 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12103 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12104 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12105 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012106 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012107 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012108 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000012109 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012110 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012111 BI.setSuccessor(0, FalseDest);
12112 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012113 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012114 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012115 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012116 return &BI;
12117 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012118
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012119 return 0;
12120}
Chris Lattner0864acf2002-11-04 16:18:53 +000012121
Chris Lattner46238a62004-07-03 00:26:11 +000012122Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12123 Value *Cond = SI.getCondition();
12124 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12125 if (I->getOpcode() == Instruction::Add)
12126 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12127 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12128 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012129 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012130 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012131 AddRHS));
12132 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000012133 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012134 return &SI;
12135 }
12136 }
12137 return 0;
12138}
12139
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012140Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012141 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012142
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012143 if (!EV.hasIndices())
12144 return ReplaceInstUsesWith(EV, Agg);
12145
12146 if (Constant *C = dyn_cast<Constant>(Agg)) {
12147 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012148 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012149
12150 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012151 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012152
12153 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12154 // Extract the element indexed by the first index out of the constant
12155 Value *V = C->getOperand(*EV.idx_begin());
12156 if (EV.getNumIndices() > 1)
12157 // Extract the remaining indices out of the constant indexed by the
12158 // first index
12159 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12160 else
12161 return ReplaceInstUsesWith(EV, V);
12162 }
12163 return 0; // Can't handle other constants
12164 }
12165 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12166 // We're extracting from an insertvalue instruction, compare the indices
12167 const unsigned *exti, *exte, *insi, *inse;
12168 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12169 exte = EV.idx_end(), inse = IV->idx_end();
12170 exti != exte && insi != inse;
12171 ++exti, ++insi) {
12172 if (*insi != *exti)
12173 // The insert and extract both reference distinctly different elements.
12174 // This means the extract is not influenced by the insert, and we can
12175 // replace the aggregate operand of the extract with the aggregate
12176 // operand of the insert. i.e., replace
12177 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12178 // %E = extractvalue { i32, { i32 } } %I, 0
12179 // with
12180 // %E = extractvalue { i32, { i32 } } %A, 0
12181 return ExtractValueInst::Create(IV->getAggregateOperand(),
12182 EV.idx_begin(), EV.idx_end());
12183 }
12184 if (exti == exte && insi == inse)
12185 // Both iterators are at the end: Index lists are identical. Replace
12186 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12187 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12188 // with "i32 42"
12189 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12190 if (exti == exte) {
12191 // The extract list is a prefix of the insert list. i.e. replace
12192 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12193 // %E = extractvalue { i32, { i32 } } %I, 1
12194 // with
12195 // %X = extractvalue { i32, { i32 } } %A, 1
12196 // %E = insertvalue { i32 } %X, i32 42, 0
12197 // by switching the order of the insert and extract (though the
12198 // insertvalue should be left in, since it may have other uses).
12199 Value *NewEV = InsertNewInstBefore(
12200 ExtractValueInst::Create(IV->getAggregateOperand(),
12201 EV.idx_begin(), EV.idx_end()),
12202 EV);
12203 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12204 insi, inse);
12205 }
12206 if (insi == inse)
12207 // The insert list is a prefix of the extract list
12208 // We can simply remove the common indices from the extract and make it
12209 // operate on the inserted value instead of the insertvalue result.
12210 // i.e., replace
12211 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12212 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12213 // with
12214 // %E extractvalue { i32 } { i32 42 }, 0
12215 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12216 exti, exte);
12217 }
12218 // Can't simplify extracts from other values. Note that nested extracts are
12219 // already simplified implicitely by the above (extract ( extract (insert) )
12220 // will be translated into extract ( insert ( extract ) ) first and then just
12221 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012222 return 0;
12223}
12224
Chris Lattner220b0cf2006-03-05 00:22:33 +000012225/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12226/// is to leave as a vector operation.
12227static bool CheapToScalarize(Value *V, bool isConstant) {
12228 if (isa<ConstantAggregateZero>(V))
12229 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012230 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012231 if (isConstant) return true;
12232 // If all elts are the same, we can extract.
12233 Constant *Op0 = C->getOperand(0);
12234 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12235 if (C->getOperand(i) != Op0)
12236 return false;
12237 return true;
12238 }
12239 Instruction *I = dyn_cast<Instruction>(V);
12240 if (!I) return false;
12241
12242 // Insert element gets simplified to the inserted element or is deleted if
12243 // this is constant idx extract element and its a constant idx insertelt.
12244 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12245 isa<ConstantInt>(I->getOperand(2)))
12246 return true;
12247 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12248 return true;
12249 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12250 if (BO->hasOneUse() &&
12251 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12252 CheapToScalarize(BO->getOperand(1), isConstant)))
12253 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012254 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12255 if (CI->hasOneUse() &&
12256 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12257 CheapToScalarize(CI->getOperand(1), isConstant)))
12258 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012259
12260 return false;
12261}
12262
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012263/// Read and decode a shufflevector mask.
12264///
12265/// It turns undef elements into values that are larger than the number of
12266/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012267static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12268 unsigned NElts = SVI->getType()->getNumElements();
12269 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12270 return std::vector<unsigned>(NElts, 0);
12271 if (isa<UndefValue>(SVI->getOperand(2)))
12272 return std::vector<unsigned>(NElts, 2*NElts);
12273
12274 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012275 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012276 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12277 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012278 Result.push_back(NElts*2); // undef -> 8
12279 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012280 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012281 return Result;
12282}
12283
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012284/// FindScalarElement - Given a vector and an element number, see if the scalar
12285/// value is already around as a register, for example if it were inserted then
12286/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012287static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012288 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012289 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12290 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012291 unsigned Width = PTy->getNumElements();
12292 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012293 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012294
12295 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012296 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012297 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012298 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012299 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012300 return CP->getOperand(EltNo);
12301 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12302 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012303 if (!isa<ConstantInt>(III->getOperand(2)))
12304 return 0;
12305 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012306
12307 // If this is an insert to the element we are looking for, return the
12308 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012309 if (EltNo == IIElt)
12310 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012311
12312 // Otherwise, the insertelement doesn't modify the value, recurse on its
12313 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012314 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012315 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012316 unsigned LHSWidth =
12317 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012318 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012319 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012320 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012321 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012322 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012323 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012324 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012325 }
12326
12327 // Otherwise, we don't know.
12328 return 0;
12329}
12330
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012331Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012332 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012333 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012334 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012335
Dan Gohman07a96762007-07-16 14:29:03 +000012336 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012337 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012338 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012339
Reid Spencer9d6565a2007-02-15 02:26:10 +000012340 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012341 // If vector val is constant with all elements the same, replace EI with
12342 // that element. When the elements are not identical, we cannot replace yet
12343 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012344 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012345 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012346 if (C->getOperand(i) != op0) {
12347 op0 = 0;
12348 break;
12349 }
12350 if (op0)
12351 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012352 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012353
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012354 // If extracting a specified index from the vector, see if we can recursively
12355 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012356 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012357 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedman76e7ba82009-07-18 19:04:16 +000012358 unsigned VectorWidth =
12359 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012360
12361 // If this is extracting an invalid index, turn this into undef, to avoid
12362 // crashing the code below.
12363 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012364 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012365
Chris Lattner867b99f2006-10-05 06:55:50 +000012366 // This instruction only demands the single element from the input vector.
12367 // If the input vector has a single use, simplify it based on this use
12368 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012369 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012370 APInt UndefElts(VectorWidth, 0);
12371 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012372 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012373 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012374 EI.setOperand(0, V);
12375 return &EI;
12376 }
12377 }
12378
Owen Andersond672ecb2009-07-03 00:17:18 +000012379 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012380 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012381
12382 // If the this extractelement is directly using a bitcast from a vector of
12383 // the same number of elements, see if we can find the source element from
12384 // it. In this case, we will end up needing to bitcast the scalars.
12385 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12386 if (const VectorType *VT =
12387 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12388 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012389 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12390 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012391 return new BitCastInst(Elt, EI.getType());
12392 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012393 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012394
Chris Lattner73fa49d2006-05-25 22:53:38 +000012395 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012396 if (I->hasOneUse()) {
12397 // Push extractelement into predecessor operation if legal and
12398 // profitable to do so
12399 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012400 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12401 if (CheapToScalarize(BO, isConstantElt)) {
12402 ExtractElementInst *newEI0 =
Eric Christophera3500da2009-07-25 02:28:41 +000012403 ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
Chris Lattner220b0cf2006-03-05 00:22:33 +000012404 EI.getName()+".lhs");
12405 ExtractElementInst *newEI1 =
Eric Christophera3500da2009-07-25 02:28:41 +000012406 ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
Chris Lattner220b0cf2006-03-05 00:22:33 +000012407 EI.getName()+".rhs");
12408 InsertNewInstBefore(newEI0, EI);
12409 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012410 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012411 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012412 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012413 unsigned AS =
12414 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012415 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Mon P Wang7c4efa62009-08-13 05:12:13 +000012416 PointerType::get(EI.getType(), AS),*I);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012417 GetElementPtrInst *GEP =
12418 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmand6aa02d2009-07-28 01:40:03 +000012419 cast<GEPOperator>(GEP)->setIsInBounds(true);
Mon P Wang7c4efa62009-08-13 05:12:13 +000012420 InsertNewInstBefore(GEP, *I);
12421 LoadInst* Load = new LoadInst(GEP, "tmp");
12422 InsertNewInstBefore(Load, *I);
12423 return ReplaceInstUsesWith(EI, Load);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012424 }
12425 }
12426 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12427 // Extracting the inserted element?
12428 if (IE->getOperand(2) == EI.getOperand(1))
12429 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12430 // If the inserted and extracted elements are constants, they must not
12431 // be the same value, extract from the pre-inserted value instead.
12432 if (isa<Constant>(IE->getOperand(2)) &&
12433 isa<Constant>(EI.getOperand(1))) {
12434 AddUsesToWorkList(EI);
12435 EI.setOperand(0, IE->getOperand(0));
12436 return &EI;
12437 }
12438 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12439 // If this is extracting an element from a shufflevector, figure out where
12440 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012441 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12442 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012443 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012444 unsigned LHSWidth =
12445 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12446
12447 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012448 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012449 else if (SrcIdx < LHSWidth*2) {
12450 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012451 Src = SVI->getOperand(1);
12452 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012453 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012454 }
Eric Christophera3500da2009-07-25 02:28:41 +000012455 return ExtractElementInst::Create(Src,
Owen Anderson1d0be152009-08-13 21:58:54 +000012456 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012457 }
12458 }
Eli Friedman2451a642009-07-18 23:06:53 +000012459 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012460 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012461 return 0;
12462}
12463
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012464/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12465/// elements from either LHS or RHS, return the shuffle mask and true.
12466/// Otherwise, return false.
12467static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012468 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012469 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012470 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12471 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012472 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012473
12474 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012475 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012476 return true;
12477 } else if (V == LHS) {
12478 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012479 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012480 return true;
12481 } else if (V == RHS) {
12482 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012483 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012484 return true;
12485 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12486 // If this is an insert of an extract from some other vector, include it.
12487 Value *VecOp = IEI->getOperand(0);
12488 Value *ScalarOp = IEI->getOperand(1);
12489 Value *IdxOp = IEI->getOperand(2);
12490
Chris Lattnerd929f062006-04-27 21:14:21 +000012491 if (!isa<ConstantInt>(IdxOp))
12492 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012493 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012494
12495 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12496 // Okay, we can handle this if the vector we are insertinting into is
12497 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012498 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012499 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012500 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012501 return true;
12502 }
12503 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12504 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012505 EI->getOperand(0)->getType() == V->getType()) {
12506 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012507 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012508
12509 // This must be extracting from either LHS or RHS.
12510 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12511 // Okay, we can handle this if the vector we are insertinting into is
12512 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012513 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012514 // If so, update the mask to reflect the inserted value.
12515 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012516 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012517 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012518 } else {
12519 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012520 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012521 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012522
12523 }
12524 return true;
12525 }
12526 }
12527 }
12528 }
12529 }
12530 // TODO: Handle shufflevector here!
12531
12532 return false;
12533}
12534
12535/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12536/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12537/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012538static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012539 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012540 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012541 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012542 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012543 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012544
12545 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012546 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012547 return V;
12548 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012549 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012550 return V;
12551 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12552 // If this is an insert of an extract from some other vector, include it.
12553 Value *VecOp = IEI->getOperand(0);
12554 Value *ScalarOp = IEI->getOperand(1);
12555 Value *IdxOp = IEI->getOperand(2);
12556
12557 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12558 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12559 EI->getOperand(0)->getType() == V->getType()) {
12560 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012561 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12562 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012563
12564 // Either the extracted from or inserted into vector must be RHSVec,
12565 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012566 if (EI->getOperand(0) == RHS || RHS == 0) {
12567 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012568 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012569 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012570 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012571 return V;
12572 }
12573
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012574 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012575 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12576 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012577 // Everything but the extracted element is replaced with the RHS.
12578 for (unsigned i = 0; i != NumElts; ++i) {
12579 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012580 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012581 }
12582 return V;
12583 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012584
12585 // If this insertelement is a chain that comes from exactly these two
12586 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012587 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12588 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012589 return EI->getOperand(0);
12590
Chris Lattnerefb47352006-04-15 01:39:45 +000012591 }
12592 }
12593 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012594 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012595
12596 // Otherwise, can't do anything fancy. Return an identity vector.
12597 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012598 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012599 return V;
12600}
12601
12602Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12603 Value *VecOp = IE.getOperand(0);
12604 Value *ScalarOp = IE.getOperand(1);
12605 Value *IdxOp = IE.getOperand(2);
12606
Chris Lattner599ded12007-04-09 01:11:16 +000012607 // Inserting an undef or into an undefined place, remove this.
12608 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12609 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012610
Chris Lattnerefb47352006-04-15 01:39:45 +000012611 // If the inserted element was extracted from some other vector, and if the
12612 // indexes are constant, try to turn this into a shufflevector operation.
12613 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12614 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12615 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012616 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012617 unsigned ExtractedIdx =
12618 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012619 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012620
12621 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12622 return ReplaceInstUsesWith(IE, VecOp);
12623
12624 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012625 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012626
12627 // If we are extracting a value from a vector, then inserting it right
12628 // back into the same place, just use the input vector.
12629 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12630 return ReplaceInstUsesWith(IE, VecOp);
12631
12632 // We could theoretically do this for ANY input. However, doing so could
12633 // turn chains of insertelement instructions into a chain of shufflevector
12634 // instructions, and right now we do not merge shufflevectors. As such,
12635 // only do this in a situation where it is clear that there is benefit.
12636 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12637 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12638 // the values of VecOp, except then one read from EIOp0.
12639 // Build a new shuffle mask.
12640 std::vector<Constant*> Mask;
12641 if (isa<UndefValue>(VecOp))
Owen Anderson1d0be152009-08-13 21:58:54 +000012642 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012643 else {
12644 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Anderson1d0be152009-08-13 21:58:54 +000012645 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
Chris Lattnerefb47352006-04-15 01:39:45 +000012646 NumVectorElts));
12647 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012648 Mask[InsertedIdx] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012649 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012650 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012651 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012652 }
12653
12654 // If this insertelement isn't used by some other insertelement, turn it
12655 // (and any insertelements it points to), into one big shuffle.
12656 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12657 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012658 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012659 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012660 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012661 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012662 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012663 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012664 }
12665 }
12666 }
12667
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012668 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12669 APInt UndefElts(VWidth, 0);
12670 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12671 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12672 return &IE;
12673
Chris Lattnerefb47352006-04-15 01:39:45 +000012674 return 0;
12675}
12676
12677
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012678Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12679 Value *LHS = SVI.getOperand(0);
12680 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012681 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012682
12683 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012684
Chris Lattner867b99f2006-10-05 06:55:50 +000012685 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012686 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012687 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012688
Dan Gohman488fbfc2008-09-09 18:11:14 +000012689 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012690
12691 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12692 return 0;
12693
Evan Cheng388df622009-02-03 10:05:09 +000012694 APInt UndefElts(VWidth, 0);
12695 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12696 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012697 LHS = SVI.getOperand(0);
12698 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012699 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012700 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012701
Chris Lattner863bcff2006-05-25 23:48:38 +000012702 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12703 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12704 if (LHS == RHS || isa<UndefValue>(LHS)) {
12705 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012706 // shuffle(undef,undef,mask) -> undef.
12707 return ReplaceInstUsesWith(SVI, LHS);
12708 }
12709
Chris Lattner863bcff2006-05-25 23:48:38 +000012710 // Remap any references to RHS to use LHS.
12711 std::vector<Constant*> Elts;
12712 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012713 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012714 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012715 else {
12716 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012717 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012718 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012719 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012720 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012721 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012722 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012723 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012724 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012725 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012726 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012727 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012728 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012729 LHS = SVI.getOperand(0);
12730 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012731 MadeChange = true;
12732 }
12733
Chris Lattner7b2e27922006-05-26 00:29:06 +000012734 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012735 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012736
Chris Lattner863bcff2006-05-25 23:48:38 +000012737 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12738 if (Mask[i] >= e*2) continue; // Ignore undef values.
12739 // Is this an identity shuffle of the LHS value?
12740 isLHSID &= (Mask[i] == i);
12741
12742 // Is this an identity shuffle of the RHS value?
12743 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012744 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012745
Chris Lattner863bcff2006-05-25 23:48:38 +000012746 // Eliminate identity shuffles.
12747 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12748 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012749
Chris Lattner7b2e27922006-05-26 00:29:06 +000012750 // If the LHS is a shufflevector itself, see if we can combine it with this
12751 // one without producing an unusual shuffle. Here we are really conservative:
12752 // we are absolutely afraid of producing a shuffle mask not in the input
12753 // program, because the code gen may not be smart enough to turn a merged
12754 // shuffle into two specific shuffles: it may produce worse code. As such,
12755 // we only merge two shuffles if the result is one of the two input shuffle
12756 // masks. In this case, merging the shuffles just removes one instruction,
12757 // which we know is safe. This is good for things like turning:
12758 // (splat(splat)) -> splat.
12759 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12760 if (isa<UndefValue>(RHS)) {
12761 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12762
12763 std::vector<unsigned> NewMask;
12764 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12765 if (Mask[i] >= 2*e)
12766 NewMask.push_back(2*e);
12767 else
12768 NewMask.push_back(LHSMask[Mask[i]]);
12769
12770 // If the result mask is equal to the src shuffle or this shuffle mask, do
12771 // the replacement.
12772 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012773 unsigned LHSInNElts =
12774 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012775 std::vector<Constant*> Elts;
12776 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012777 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012778 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012779 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012780 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012781 }
12782 }
12783 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12784 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012785 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012786 }
12787 }
12788 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012789
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012790 return MadeChange ? &SVI : 0;
12791}
12792
12793
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012794
Chris Lattnerea1c4542004-12-08 23:43:58 +000012795
12796/// TryToSinkInstruction - Try to move the specified instruction from its
12797/// current block into the beginning of DestBlock, which can only happen if it's
12798/// safe to move the instruction past all of the instructions between it and the
12799/// end of its block.
12800static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12801 assert(I->hasOneUse() && "Invariants didn't hold!");
12802
Chris Lattner108e9022005-10-27 17:13:11 +000012803 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012804 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012805 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012806
Chris Lattnerea1c4542004-12-08 23:43:58 +000012807 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012808 if (isa<AllocaInst>(I) && I->getParent() ==
12809 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012810 return false;
12811
Chris Lattner96a52a62004-12-09 07:14:34 +000012812 // We can only sink load instructions if there is nothing between the load and
12813 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012814 if (I->mayReadFromMemory()) {
12815 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012816 Scan != E; ++Scan)
12817 if (Scan->mayWriteToMemory())
12818 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012819 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012820
Dan Gohman02dea8b2008-05-23 21:05:58 +000012821 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012822
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012823 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012824 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012825 ++NumSunkInst;
12826 return true;
12827}
12828
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012829
12830/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12831/// all reachable code to the worklist.
12832///
12833/// This has a couple of tricks to make the code faster and more powerful. In
12834/// particular, we constant fold and DCE instructions as we go, to avoid adding
12835/// them to the worklist (this significantly speeds up instcombine on code where
12836/// many instructions are dead or constant). Additionally, if we find a branch
12837/// whose condition is a known constant, we only visit the reachable successors.
12838///
12839static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012840 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012841 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012842 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012843 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012844 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012845
Chris Lattner2c7718a2007-03-23 19:17:18 +000012846 while (!Worklist.empty()) {
12847 BB = Worklist.back();
12848 Worklist.pop_back();
12849
12850 // We have now visited this block! If we've already been here, ignore it.
12851 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012852
12853 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012854 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12855 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012856
Chris Lattner2c7718a2007-03-23 19:17:18 +000012857 // DCE instruction if trivially dead.
12858 if (isInstructionTriviallyDead(Inst)) {
12859 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012860 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012861 Inst->eraseFromParent();
12862 continue;
12863 }
12864
12865 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012866 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012867 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12868 << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012869 Inst->replaceAllUsesWith(C);
12870 ++NumConstProp;
12871 Inst->eraseFromParent();
12872 continue;
12873 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012874
Devang Patel7fe1dec2008-11-19 18:56:50 +000012875 // If there are two consecutive llvm.dbg.stoppoint calls then
12876 // it is likely that the optimizer deleted code in between these
12877 // two intrinsics.
12878 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12879 if (DBI_Next) {
12880 if (DBI_Prev
12881 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12882 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12883 IC.RemoveFromWorkList(DBI_Prev);
12884 DBI_Prev->eraseFromParent();
12885 }
12886 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012887 } else {
12888 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012889 }
12890
Chris Lattner2c7718a2007-03-23 19:17:18 +000012891 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012892 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012893
12894 // Recursively visit successors. If this is a branch or switch on a
12895 // constant, only visit the reachable successor.
12896 TerminatorInst *TI = BB->getTerminator();
12897 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12898 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12899 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012900 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012901 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012902 continue;
12903 }
12904 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12905 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12906 // See if this is an explicit destination.
12907 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12908 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012909 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012910 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012911 continue;
12912 }
12913
12914 // Otherwise it is the default destination.
12915 Worklist.push_back(SI->getSuccessor(0));
12916 continue;
12917 }
12918 }
12919
12920 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12921 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012922 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012923}
12924
Chris Lattnerec9c3582007-03-03 02:04:50 +000012925bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012926 bool Changed = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012927 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012928
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012929 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12930 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012931
Chris Lattnerb3d59702005-07-07 20:40:38 +000012932 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012933 // Do a depth-first traversal of the function, populate the worklist with
12934 // the reachable instructions. Ignore blocks that are not reachable. Keep
12935 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012936 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012937 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012938
Chris Lattnerb3d59702005-07-07 20:40:38 +000012939 // Do a quick scan over the function. If we find any blocks that are
12940 // unreachable, remove any instructions inside of them. This prevents
12941 // the instcombine code from having to deal with some bad special cases.
12942 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12943 if (!Visited.count(BB)) {
12944 Instruction *Term = BB->getTerminator();
12945 while (Term != BB->begin()) { // Remove instrs bottom-up
12946 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012947
Chris Lattnerbdff5482009-08-23 04:37:46 +000012948 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012949 // A debug intrinsic shouldn't force another iteration if we weren't
12950 // going to do one without it.
12951 if (!isa<DbgInfoIntrinsic>(I)) {
12952 ++NumDeadInst;
12953 Changed = true;
12954 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012955 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012956 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012957 I->eraseFromParent();
12958 }
12959 }
12960 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012961
Chris Lattnerdbab3862007-03-02 21:28:56 +000012962 while (!Worklist.empty()) {
12963 Instruction *I = RemoveOneFromWorkList();
12964 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012965
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012966 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012967 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012968 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012969 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012970 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012971 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012972
Chris Lattnerbdff5482009-08-23 04:37:46 +000012973 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012974
12975 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012976 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012977 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012978 continue;
12979 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012980
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012981 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012982 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012983 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012984
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012985 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012986 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000012987 ReplaceInstUsesWith(*I, C);
12988
Chris Lattner62b14df2002-09-02 04:59:56 +000012989 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012990 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012991 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012992 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012993 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012994 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012995
Eli Friedmanfd2934f2009-07-15 22:13:34 +000012996 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012997 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012998 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12999 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000013000 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13001 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000013002 if (NewC != CE) {
13003 i->set(NewC);
13004 Changed = true;
13005 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013006 }
13007
Chris Lattnerea1c4542004-12-08 23:43:58 +000013008 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013009 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013010 BasicBlock *BB = I->getParent();
13011 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13012 if (UserParent != BB) {
13013 bool UserIsSuccessor = false;
13014 // See if the user is one of our successors.
13015 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13016 if (*SI == UserParent) {
13017 UserIsSuccessor = true;
13018 break;
13019 }
13020
13021 // If the user is one of our immediate successors, and if that successor
13022 // only has us as a predecessors (we'd have to split the critical edge
13023 // otherwise), we can keep going.
13024 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13025 next(pred_begin(UserParent)) == pred_end(UserParent))
13026 // Okay, the CFG is simple enough, try to sink this instruction.
13027 Changed |= TryToSinkInstruction(I, UserParent);
13028 }
13029 }
13030
Chris Lattner8a2a3112001-12-14 16:52:21 +000013031 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000013032#ifndef NDEBUG
13033 std::string OrigI;
13034#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000013035 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000013036 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013037 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013038 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013039 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013040 DEBUG(errs() << "IC: Old = " << *I << '\n'
13041 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000013042
Chris Lattnerf523d062004-06-09 05:08:07 +000013043 // Everything uses the new instruction now.
13044 I->replaceAllUsesWith(Result);
13045
13046 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013047 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000013048 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013049
Chris Lattner6934a042007-02-11 01:23:03 +000013050 // Move the name to the new instruction first.
13051 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013052
13053 // Insert the new instruction into the basic block...
13054 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013055 BasicBlock::iterator InsertPos = I;
13056
13057 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13058 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13059 ++InsertPos;
13060
13061 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013062
Chris Lattner00d51312004-05-01 23:27:23 +000013063 // Make sure that we reprocess all operands now that we reduced their
13064 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013065 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000013066
Chris Lattnerf523d062004-06-09 05:08:07 +000013067 // Instructions can end up on the worklist more than once. Make sure
13068 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013069 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013070
13071 // Erase the old instruction.
13072 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000013073 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013074#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000013075 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13076 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000013077#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013078
Chris Lattner90ac28c2002-08-02 19:29:35 +000013079 // If the instruction was modified, it's possible that it is now dead.
13080 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013081 if (isInstructionTriviallyDead(I)) {
13082 // Make sure we process all operands now that we are reducing their
13083 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000013084 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000013085
Chris Lattner00d51312004-05-01 23:27:23 +000013086 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013087 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013088 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000013089 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000013090 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000013091 AddToWorkList(I);
13092 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013093 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013094 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013095 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013096 }
13097 }
13098
Chris Lattnerec9c3582007-03-03 02:04:50 +000013099 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000013100
13101 // Do an explicit clear, this shrinks the map if needed.
13102 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013103 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013104}
13105
Chris Lattnerec9c3582007-03-03 02:04:50 +000013106
13107bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013108 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013109 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000013110
Chris Lattnerec9c3582007-03-03 02:04:50 +000013111 bool EverMadeChange = false;
13112
13113 // Iterate while there is work to do.
13114 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013115 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013116 EverMadeChange = true;
13117 return EverMadeChange;
13118}
13119
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013120FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013121 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013122}