blob: 4102e6ceddb514f6b63e72c60bee84c5ba960589 [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 Lattner873ff012009-08-30 05:55:36 +000077 /// InstCombineWorklist - This is the worklist management logic for
78 /// InstCombine.
79 class InstCombineWorklist {
80 SmallVector<Instruction*, 256> Worklist;
81 DenseMap<Instruction*, unsigned> WorklistMap;
82
83 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
84 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
85 public:
86 InstCombineWorklist() {}
87
88 bool isEmpty() const { return Worklist.empty(); }
89
90 /// Add - Add the specified instruction to the worklist if it isn't already
91 /// in it.
92 void Add(Instruction *I) {
93 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
94 Worklist.push_back(I);
95 }
96
97 void Remove(Instruction *I) {
98 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
99 if (It == WorklistMap.end()) return; // Not in worklist.
100
101 // Don't bother moving everything down, just null out the slot.
102 Worklist[It->second] = 0;
103
104 WorklistMap.erase(It);
105 }
106
107 Instruction *RemoveOne() {
108 Instruction *I = Worklist.back();
109 Worklist.pop_back();
110 WorklistMap.erase(I);
111 return I;
112 }
113
114
115 /// Zap - check that the worklist is empty and nuke the backing store for
116 /// the map if it is large.
117 void Zap() {
118 assert(WorklistMap.empty() && "Worklist empty, but map not?");
119
120 // Do an explicit clear, this shrinks the map if needed.
121 WorklistMap.clear();
122 }
123 };
124} // end anonymous namespace.
125
126
127namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +0000128 class VISIBILITY_HIDDEN InstCombiner
129 : public FunctionPass,
130 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000131 // Worklist of all of the instructions that need to be simplified.
Chris Lattner873ff012009-08-30 05:55:36 +0000132 InstCombineWorklist Worklist;
Chris Lattnerbc61e662003-11-02 05:57:39 +0000133 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +0000134 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +0000135 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000136 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +0000137 InstCombiner() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000138
Owen Andersone922c022009-07-22 00:24:57 +0000139 LLVMContext *Context;
140 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +0000141
Chris Lattnerdbab3862007-03-02 21:28:56 +0000142 /// AddToWorkList - Add the specified instruction to the worklist if it
143 /// isn't already in it.
144 void AddToWorkList(Instruction *I) {
Chris Lattner873ff012009-08-30 05:55:36 +0000145 Worklist.Add(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000146 }
147
148 // RemoveFromWorkList - remove I from the worklist if it exists.
149 void RemoveFromWorkList(Instruction *I) {
Chris Lattner873ff012009-08-30 05:55:36 +0000150 Worklist.Remove(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000151 }
152
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000153 /// AddUsersToWorkList - When an instruction is simplified, add all users of
154 /// the instruction to the work lists because they might get more simplified
155 /// now.
156 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000157 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000158 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000159 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000160 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000161 }
162
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000163 /// AddUsesToWorkList - When an instruction is simplified, add operands to
164 /// the work lists because they might get more simplified now.
165 ///
166 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000167 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
168 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000169 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000170 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000171
172 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
173 /// dead. Add all of its operands to the worklist, turning them into
174 /// undef's to reduce the number of uses of those instructions.
175 ///
176 /// Return the specified operand before it is turned into an undef.
177 ///
178 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
179 Value *R = I.getOperand(op);
180
Gabor Greif177dd3f2008-06-12 21:37:33 +0000181 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
182 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000183 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000184 // Set the operand to undef to drop the use.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000185 *i = UndefValue::get(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000186 }
187
188 return R;
189 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000190
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000191 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000192 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000193
194 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000195
Chris Lattner97e52e42002-04-28 21:27:06 +0000196 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000197 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000198 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000199 }
200
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000201 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000202
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000203 // Visitation implementation - Implement instruction combining for different
204 // instruction types. The semantics are as follows:
205 // Return Value:
206 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000207 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000208 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000209 //
Chris Lattner7e708292002-06-25 16:13:24 +0000210 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000211 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000212 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000213 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000214 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000215 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000216 Instruction *visitURem(BinaryOperator &I);
217 Instruction *visitSRem(BinaryOperator &I);
218 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000219 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000220 Instruction *commonRemTransforms(BinaryOperator &I);
221 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000222 Instruction *commonDivTransforms(BinaryOperator &I);
223 Instruction *commonIDivTransforms(BinaryOperator &I);
224 Instruction *visitUDiv(BinaryOperator &I);
225 Instruction *visitSDiv(BinaryOperator &I);
226 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000227 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000228 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000229 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000230 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000231 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000232 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000233 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000234 Instruction *visitOr (BinaryOperator &I);
235 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000236 Instruction *visitShl(BinaryOperator &I);
237 Instruction *visitAShr(BinaryOperator &I);
238 Instruction *visitLShr(BinaryOperator &I);
239 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000240 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
241 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000242 Instruction *visitFCmpInst(FCmpInst &I);
243 Instruction *visitICmpInst(ICmpInst &I);
244 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000245 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
246 Instruction *LHS,
247 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000248 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
249 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000250
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000251 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000252 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000253 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000254 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000255 Instruction *commonCastTransforms(CastInst &CI);
256 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000257 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000258 Instruction *visitTrunc(TruncInst &CI);
259 Instruction *visitZExt(ZExtInst &CI);
260 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000261 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000262 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000263 Instruction *visitFPToUI(FPToUIInst &FI);
264 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000265 Instruction *visitUIToFP(CastInst &CI);
266 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000267 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000268 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000269 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000270 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
271 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000272 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000273 Instruction *visitSelectInst(SelectInst &SI);
274 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000275 Instruction *visitCallInst(CallInst &CI);
276 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000277 Instruction *visitPHINode(PHINode &PN);
278 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000279 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000280 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000281 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000282 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000283 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000284 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000285 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000286 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000287 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000288 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000289
290 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000291 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000292
Chris Lattner9fe38862003-06-19 17:00:31 +0000293 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000294 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000295 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000296 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000297 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
298 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000299 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000300 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
301
Chris Lattner9fe38862003-06-19 17:00:31 +0000302
Chris Lattner28977af2004-04-05 01:30:19 +0000303 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000304 // InsertNewInstBefore - insert an instruction New before instruction Old
305 // in the program. Add the new instruction to the worklist.
306 //
Chris Lattner955f3312004-09-28 21:48:02 +0000307 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000308 assert(New && New->getParent() == 0 &&
309 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000310 BasicBlock *BB = Old.getParent();
311 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000312 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000313 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000314 }
315
Chris Lattner0c967662004-09-24 15:21:34 +0000316 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
317 /// This also adds the cast to the worklist. Finally, this returns the
318 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000319 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
320 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000321 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000322
Chris Lattnere2ed0572006-04-06 19:19:17 +0000323 if (Constant *CV = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000324 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000325
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000326 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000327 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000328 return C;
329 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000330
331 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
332 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
333 }
334
Chris Lattner0c967662004-09-24 15:21:34 +0000335
Chris Lattner8b170942002-08-09 23:47:40 +0000336 // ReplaceInstUsesWith - This method is to be used when an instruction is
337 // found to be dead, replacable with another preexisting expression. Here
338 // we add all uses of I to the worklist, replace all uses of I with the new
339 // value, then return I, so that the inst combiner will know that I was
340 // modified.
341 //
342 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000343 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000344 if (&I != V) {
345 I.replaceAllUsesWith(V);
346 return &I;
347 } else {
348 // If we are replacing the instruction with itself, this must be in a
349 // segment of unreachable code, so just clobber the instruction.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000350 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000351 return &I;
352 }
Chris Lattner8b170942002-08-09 23:47:40 +0000353 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000354
355 // EraseInstFromFunction - When dealing with an instruction that has side
356 // effects or produces a void value, we can't rely on DCE to delete the
357 // instruction. Instead, visit methods should return the value returned by
358 // this function.
359 Instruction *EraseInstFromFunction(Instruction &I) {
360 assert(I.use_empty() && "Cannot erase instruction that is used!");
361 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000362 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000363 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000364 return 0; // Don't do anything with FI
365 }
Chris Lattner173234a2008-06-02 01:18:21 +0000366
367 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
368 APInt &KnownOne, unsigned Depth = 0) const {
369 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
370 }
371
372 bool MaskedValueIsZero(Value *V, const APInt &Mask,
373 unsigned Depth = 0) const {
374 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
375 }
376 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
377 return llvm::ComputeNumSignBits(Op, TD, Depth);
378 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000379
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000380 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000381
Reid Spencere4d87aa2006-12-23 06:05:41 +0000382 /// SimplifyCommutative - This performs a few simplifications for
383 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000384 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000385
Reid Spencere4d87aa2006-12-23 06:05:41 +0000386 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
387 /// most-complex to least-complex order.
388 bool SimplifyCompare(CmpInst &I);
389
Chris Lattner886ab6c2009-01-31 08:15:18 +0000390 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
391 /// based on the demanded bits.
392 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
393 APInt& KnownZero, APInt& KnownOne,
394 unsigned Depth);
395 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000396 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000397 unsigned Depth=0);
398
399 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
400 /// SimplifyDemandedBits knows about. See if the instruction has any
401 /// properties that allow us to simplify its operands.
402 bool SimplifyDemandedInstructionBits(Instruction &Inst);
403
Evan Cheng388df622009-02-03 10:05:09 +0000404 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
405 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000406
Chris Lattner4e998b22004-09-29 05:07:12 +0000407 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
408 // PHI node as operand #0, see if we can fold the instruction into the PHI
409 // (which is only possible if all operands to the PHI are constants).
410 Instruction *FoldOpIntoPhi(Instruction &I);
411
Chris Lattnerbac32862004-11-14 19:13:23 +0000412 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
413 // operator and they all are only used by the PHI, PHI together their
414 // inputs, and do the operation once, to the result of the PHI.
415 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000416 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000417 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
418
Chris Lattner7da52b22006-11-01 04:51:18 +0000419
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000420 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
421 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000422
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000423 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000424 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000425 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000426 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000427 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000428 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000429 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000430 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000431 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000432
Chris Lattnerafe91a52006-06-15 19:07:26 +0000433
Reid Spencerc55b2432006-12-13 18:21:21 +0000434 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000435
Dan Gohman6de29f82009-06-15 22:12:54 +0000436 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000437 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000438 unsigned GetOrEnforceKnownAlignment(Value *V,
439 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000440
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000441 };
Chris Lattner873ff012009-08-30 05:55:36 +0000442} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000443
Dan Gohman844731a2008-05-13 00:00:25 +0000444char InstCombiner::ID = 0;
445static RegisterPass<InstCombiner>
446X("instcombine", "Combine redundant instructions");
447
Chris Lattner4f98c562003-03-10 21:43:22 +0000448// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000449// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000450static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000451 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000452 if (BinaryOperator::isNeg(V) ||
453 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000454 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000455 return 3;
456 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000457 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000458 if (isa<Argument>(V)) return 3;
459 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000460}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000461
Chris Lattnerc8802d22003-03-11 00:12:48 +0000462// isOnlyUse - Return true if this instruction will be deleted if we stop using
463// it.
464static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000465 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000466}
467
Chris Lattner4cb170c2004-02-23 06:38:22 +0000468// getPromotedType - Return the specified type promoted as it would be to pass
469// though a va_arg area...
470static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000471 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
472 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000473 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000474 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000475 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000476}
477
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000478/// getBitCastOperand - If the specified operand is a CastInst, a constant
479/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
480/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000481static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000482 if (Operator *O = dyn_cast<Operator>(V)) {
483 if (O->getOpcode() == Instruction::BitCast)
484 return O->getOperand(0);
485 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
486 if (GEP->hasAllZeroIndices())
487 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000488 }
Chris Lattnereed48272005-09-13 00:40:14 +0000489 return 0;
490}
491
Reid Spencer3da59db2006-11-27 01:05:10 +0000492/// This function is a wrapper around CastInst::isEliminableCastPair. It
493/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000494static Instruction::CastOps
495isEliminableCastPair(
496 const CastInst *CI, ///< The first cast instruction
497 unsigned opcode, ///< The opcode of the second cast instruction
498 const Type *DstTy, ///< The target type for the second cast instruction
499 TargetData *TD ///< The target data for pointer size
500) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000501
Reid Spencer3da59db2006-11-27 01:05:10 +0000502 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
503 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000504
Reid Spencer3da59db2006-11-27 01:05:10 +0000505 // Get the opcodes of the two Cast instructions
506 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
507 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000508
Chris Lattnera0e69692009-03-24 18:35:40 +0000509 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000510 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000511 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000512
513 // We don't want to form an inttoptr or ptrtoint that converts to an integer
514 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000515 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000516 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000517 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000518 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000519 Res = 0;
520
521 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000522}
523
524/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
525/// in any code being generated. It does not require codegen if V is simple
526/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000527static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
528 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000529 if (V->getType() == Ty || isa<Constant>(V)) return false;
530
Chris Lattner01575b72006-05-25 23:24:33 +0000531 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000532 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000533 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000534 return false;
535 return true;
536}
537
Chris Lattner4f98c562003-03-10 21:43:22 +0000538// SimplifyCommutative - This performs a few simplifications for commutative
539// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000540//
Chris Lattner4f98c562003-03-10 21:43:22 +0000541// 1. Order operands such that they are listed from right (least complex) to
542// left (most complex). This puts constants before unary operators before
543// binary operators.
544//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000545// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
546// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000547//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000548bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000549 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000550 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000551 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000552
Chris Lattner4f98c562003-03-10 21:43:22 +0000553 if (!I.isAssociative()) return Changed;
554 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000555 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
556 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
557 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000558 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000559 cast<Constant>(I.getOperand(1)),
560 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000561 I.setOperand(0, Op->getOperand(0));
562 I.setOperand(1, Folded);
563 return true;
564 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
565 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
566 isOnlyUse(Op) && isOnlyUse(Op1)) {
567 Constant *C1 = cast<Constant>(Op->getOperand(1));
568 Constant *C2 = cast<Constant>(Op1->getOperand(1));
569
570 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000571 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000572 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000573 Op1->getOperand(0),
574 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000575 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000576 I.setOperand(0, New);
577 I.setOperand(1, Folded);
578 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000579 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000580 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000581 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000582}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000583
Reid Spencere4d87aa2006-12-23 06:05:41 +0000584/// SimplifyCompare - For a CmpInst this function just orders the operands
585/// so that theyare listed from right (least complex) to left (most complex).
586/// This puts constants before unary operators before binary operators.
587bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman14ef4f02009-08-29 23:39:38 +0000588 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000589 return false;
590 I.swapOperands();
591 // Compare instructions are not associative so there's nothing else we can do.
592 return true;
593}
594
Chris Lattner8d969642003-03-10 23:06:50 +0000595// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
596// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000597//
Dan Gohman186a6362009-08-12 16:04:34 +0000598static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000599 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000600 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000601
Chris Lattner0ce85802004-12-14 20:08:06 +0000602 // Constants can be considered to be negated values if they can be folded.
603 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000604 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000605
606 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
607 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000608 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000609
Chris Lattner8d969642003-03-10 23:06:50 +0000610 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000611}
612
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000613// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
614// instruction if the LHS is a constant negative zero (which is the 'negate'
615// form).
616//
Dan Gohman186a6362009-08-12 16:04:34 +0000617static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000618 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000619 return BinaryOperator::getFNegArgument(V);
620
621 // Constants can be considered to be negated values if they can be folded.
622 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000623 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000624
625 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
626 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000627 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000628
629 return 0;
630}
631
Dan Gohman186a6362009-08-12 16:04:34 +0000632static inline Value *dyn_castNotVal(Value *V) {
Chris Lattner8d969642003-03-10 23:06:50 +0000633 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000634 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000635
636 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000637 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000638 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000639 return 0;
640}
641
Chris Lattnerc8802d22003-03-11 00:12:48 +0000642// dyn_castFoldableMul - If this value is a multiply that can be folded into
643// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000644// non-constant operand of the multiply, and set CST to point to the multiplier.
645// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000646//
Dan Gohman186a6362009-08-12 16:04:34 +0000647static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000648 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000649 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000650 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000651 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000652 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000653 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000654 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000655 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000656 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000657 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000658 CST = ConstantInt::get(V->getType()->getContext(),
659 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000660 return I->getOperand(0);
661 }
662 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000663 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000664}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000665
Reid Spencer7177c3a2007-03-25 05:33:51 +0000666/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000667static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000668 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000669 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000670}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000671/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000672static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000673 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000674 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000675}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000676/// MultiplyOverflows - True if the multiply can not be expressed in an int
677/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000678static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000679 uint32_t W = C1->getBitWidth();
680 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
681 if (sign) {
682 LHSExt.sext(W * 2);
683 RHSExt.sext(W * 2);
684 } else {
685 LHSExt.zext(W * 2);
686 RHSExt.zext(W * 2);
687 }
688
689 APInt MulExt = LHSExt * RHSExt;
690
691 if (sign) {
692 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
693 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
694 return MulExt.slt(Min) || MulExt.sgt(Max);
695 } else
696 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
697}
Chris Lattner955f3312004-09-28 21:48:02 +0000698
Reid Spencere7816b52007-03-08 01:52:58 +0000699
Chris Lattner255d8912006-02-11 09:31:47 +0000700/// ShrinkDemandedConstant - Check to see if the specified operand of the
701/// specified instruction is a constant integer. If so, check to see if there
702/// are any bits set in the constant that are not demanded. If so, shrink the
703/// constant and return true.
704static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000705 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000706 assert(I && "No instruction?");
707 assert(OpNo < I->getNumOperands() && "Operand index too large");
708
709 // If the operand is not a constant integer, nothing to do.
710 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
711 if (!OpC) return false;
712
713 // If there are no bits set that aren't demanded, nothing to do.
714 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
715 if ((~Demanded & OpC->getValue()) == 0)
716 return false;
717
718 // This instruction is producing bits that are not demanded. Shrink the RHS.
719 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000720 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000721 return true;
722}
723
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000724// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
725// set of known zero and one bits, compute the maximum and minimum values that
726// could have the specified known zero and known one bits, returning them in
727// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000728static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000729 const APInt& KnownOne,
730 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000731 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
732 KnownZero.getBitWidth() == Min.getBitWidth() &&
733 KnownZero.getBitWidth() == Max.getBitWidth() &&
734 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000735 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000736
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000737 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
738 // bit if it is unknown.
739 Min = KnownOne;
740 Max = KnownOne|UnknownBits;
741
Dan Gohman1c8491e2009-04-25 17:12:48 +0000742 if (UnknownBits.isNegative()) { // Sign bit is unknown
743 Min.set(Min.getBitWidth()-1);
744 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000745 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000746}
747
748// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
749// a set of known zero and one bits, compute the maximum and minimum values that
750// could have the specified known zero and known one bits, returning them in
751// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000752static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000753 const APInt &KnownOne,
754 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000755 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
756 KnownZero.getBitWidth() == Min.getBitWidth() &&
757 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000758 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000759 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000760
761 // The minimum value is when the unknown bits are all zeros.
762 Min = KnownOne;
763 // The maximum value is when the unknown bits are all ones.
764 Max = KnownOne|UnknownBits;
765}
Chris Lattner255d8912006-02-11 09:31:47 +0000766
Chris Lattner886ab6c2009-01-31 08:15:18 +0000767/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
768/// SimplifyDemandedBits knows about. See if the instruction has any
769/// properties that allow us to simplify its operands.
770bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000771 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000772 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
773 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
774
775 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
776 KnownZero, KnownOne, 0);
777 if (V == 0) return false;
778 if (V == &Inst) return true;
779 ReplaceInstUsesWith(Inst, V);
780 return true;
781}
782
783/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
784/// specified instruction operand if possible, updating it in place. It returns
785/// true if it made any change and false otherwise.
786bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
787 APInt &KnownZero, APInt &KnownOne,
788 unsigned Depth) {
789 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
790 KnownZero, KnownOne, Depth);
791 if (NewVal == 0) return false;
792 U.set(NewVal);
793 return true;
794}
795
796
797/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
798/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000799/// that only the bits set in DemandedMask of the result of V are ever used
800/// downstream. Consequently, depending on the mask and V, it may be possible
801/// to replace V with a constant or one of its operands. In such cases, this
802/// function does the replacement and returns true. In all other cases, it
803/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000804/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000805/// to be zero in the expression. These are provided to potentially allow the
806/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
807/// the expression. KnownOne and KnownZero always follow the invariant that
808/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
809/// the bits in KnownOne and KnownZero may only be accurate for those bits set
810/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
811/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000812///
813/// This returns null if it did not change anything and it permits no
814/// simplification. This returns V itself if it did some simplification of V's
815/// operands based on the information about what bits are demanded. This returns
816/// some other non-null value if it found out that V is equal to another value
817/// in the context where the specified bits are demanded, but not for all users.
818Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
819 APInt &KnownZero, APInt &KnownOne,
820 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000821 assert(V != 0 && "Null pointer of Value???");
822 assert(Depth <= 6 && "Limit Search Depth");
823 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000824 const Type *VTy = V->getType();
825 assert((TD || !isa<PointerType>(VTy)) &&
826 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000827 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
828 (!VTy->isIntOrIntVector() ||
829 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000830 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000831 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000832 "Value *V, DemandedMask, KnownZero and KnownOne "
833 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000834 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
835 // We know all of the bits for a constant!
836 KnownOne = CI->getValue() & DemandedMask;
837 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000838 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000839 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000840 if (isa<ConstantPointerNull>(V)) {
841 // We know all of the bits for a constant!
842 KnownOne.clear();
843 KnownZero = DemandedMask;
844 return 0;
845 }
846
Chris Lattner08d2cc72009-01-31 07:26:06 +0000847 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000848 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000849 if (DemandedMask == 0) { // Not demanding any bits from V.
850 if (isa<UndefValue>(V))
851 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000852 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000853 }
854
Chris Lattner4598c942009-01-31 08:24:16 +0000855 if (Depth == 6) // Limit search depth.
856 return 0;
857
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000858 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
859 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
860
Dan Gohman1c8491e2009-04-25 17:12:48 +0000861 Instruction *I = dyn_cast<Instruction>(V);
862 if (!I) {
863 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
864 return 0; // Only analyze instructions.
865 }
866
Chris Lattner4598c942009-01-31 08:24:16 +0000867 // If there are multiple uses of this value and we aren't at the root, then
868 // we can't do any simplifications of the operands, because DemandedMask
869 // only reflects the bits demanded by *one* of the users.
870 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000871 // Despite the fact that we can't simplify this instruction in all User's
872 // context, we can at least compute the knownzero/knownone bits, and we can
873 // do simplifications that apply to *just* the one user if we know that
874 // this instruction has a simpler value in that context.
875 if (I->getOpcode() == Instruction::And) {
876 // If either the LHS or the RHS are Zero, the result is zero.
877 ComputeMaskedBits(I->getOperand(1), DemandedMask,
878 RHSKnownZero, RHSKnownOne, Depth+1);
879 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
880 LHSKnownZero, LHSKnownOne, Depth+1);
881
882 // If all of the demanded bits are known 1 on one side, return the other.
883 // These bits cannot contribute to the result of the 'and' in this
884 // context.
885 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
886 (DemandedMask & ~LHSKnownZero))
887 return I->getOperand(0);
888 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
889 (DemandedMask & ~RHSKnownZero))
890 return I->getOperand(1);
891
892 // If all of the demanded bits in the inputs are known zeros, return zero.
893 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000894 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000895
896 } else if (I->getOpcode() == Instruction::Or) {
897 // We can simplify (X|Y) -> X or Y in the user's context if we know that
898 // only bits from X or Y are demanded.
899
900 // If either the LHS or the RHS are One, the result is One.
901 ComputeMaskedBits(I->getOperand(1), DemandedMask,
902 RHSKnownZero, RHSKnownOne, Depth+1);
903 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
904 LHSKnownZero, LHSKnownOne, Depth+1);
905
906 // If all of the demanded bits are known zero on one side, return the
907 // other. These bits cannot contribute to the result of the 'or' in this
908 // context.
909 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
910 (DemandedMask & ~LHSKnownOne))
911 return I->getOperand(0);
912 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
913 (DemandedMask & ~RHSKnownOne))
914 return I->getOperand(1);
915
916 // If all of the potentially set bits on one side are known to be set on
917 // the other side, just use the 'other' side.
918 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
919 (DemandedMask & (~RHSKnownZero)))
920 return I->getOperand(0);
921 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
922 (DemandedMask & (~LHSKnownZero)))
923 return I->getOperand(1);
924 }
925
Chris Lattner4598c942009-01-31 08:24:16 +0000926 // Compute the KnownZero/KnownOne bits to simplify things downstream.
927 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
928 return 0;
929 }
930
931 // If this is the root being simplified, allow it to have multiple uses,
932 // just set the DemandedMask to all bits so that we can try to simplify the
933 // operands. This allows visitTruncInst (for example) to simplify the
934 // operand of a trunc without duplicating all the logic below.
935 if (Depth == 0 && !V->hasOneUse())
936 DemandedMask = APInt::getAllOnesValue(BitWidth);
937
Reid Spencer8cb68342007-03-12 17:25:59 +0000938 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000939 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000940 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000941 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000942 case Instruction::And:
943 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000944 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
945 RHSKnownZero, RHSKnownOne, Depth+1) ||
946 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000947 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000948 return I;
949 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
950 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000951
952 // If all of the demanded bits are known 1 on one side, return the other.
953 // These bits cannot contribute to the result of the 'and'.
954 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
955 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000956 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000957 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
958 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000959 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000960
961 // If all of the demanded bits in the inputs are known zeros, return zero.
962 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000963 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000964
965 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000966 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000967 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000968
969 // Output known-1 bits are only known if set in both the LHS & RHS.
970 RHSKnownOne &= LHSKnownOne;
971 // Output known-0 are known to be clear if zero in either the LHS | RHS.
972 RHSKnownZero |= LHSKnownZero;
973 break;
974 case Instruction::Or:
975 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000976 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
977 RHSKnownZero, RHSKnownOne, Depth+1) ||
978 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000979 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000980 return I;
981 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
982 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000983
984 // If all of the demanded bits are known zero on one side, return the other.
985 // These bits cannot contribute to the result of the 'or'.
986 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
987 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000988 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000989 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
990 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000991 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000992
993 // If all of the potentially set bits on one side are known to be set on
994 // the other side, just use the 'other' side.
995 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
996 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000997 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000998 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
999 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001000 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001001
1002 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001003 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001004 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001005
1006 // Output known-0 bits are only known if clear in both the LHS & RHS.
1007 RHSKnownZero &= LHSKnownZero;
1008 // Output known-1 are known to be set if set in either the LHS | RHS.
1009 RHSKnownOne |= LHSKnownOne;
1010 break;
1011 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001012 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1013 RHSKnownZero, RHSKnownOne, Depth+1) ||
1014 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001015 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001016 return I;
1017 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1018 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001019
1020 // If all of the demanded bits are known zero on one side, return the other.
1021 // These bits cannot contribute to the result of the 'xor'.
1022 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001023 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001024 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001025 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001026
1027 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1028 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1029 (RHSKnownOne & LHSKnownOne);
1030 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1031 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1032 (RHSKnownOne & LHSKnownZero);
1033
1034 // If all of the demanded bits are known to be zero on one side or the
1035 // other, turn this into an *inclusive* or.
1036 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1037 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1038 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001039 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001040 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001041 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001042 }
1043
1044 // If all of the demanded bits on one side are known, and all of the set
1045 // bits on that side are also known to be set on the other side, turn this
1046 // into an AND, as we know the bits will be cleared.
1047 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1048 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1049 // all known
1050 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001051 Constant *AndC = Constant::getIntegerValue(VTy,
1052 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001053 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001054 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001055 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001056 }
1057 }
1058
1059 // If the RHS is a constant, see if we can simplify it.
1060 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001061 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001062 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001063
1064 RHSKnownZero = KnownZeroOut;
1065 RHSKnownOne = KnownOneOut;
1066 break;
1067 }
1068 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001069 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1070 RHSKnownZero, RHSKnownOne, Depth+1) ||
1071 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001072 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001073 return I;
1074 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1075 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001076
1077 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001078 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1079 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001080 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001081
1082 // Only known if known in both the LHS and RHS.
1083 RHSKnownOne &= LHSKnownOne;
1084 RHSKnownZero &= LHSKnownZero;
1085 break;
1086 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001087 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001088 DemandedMask.zext(truncBf);
1089 RHSKnownZero.zext(truncBf);
1090 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001091 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001092 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001093 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001094 DemandedMask.trunc(BitWidth);
1095 RHSKnownZero.trunc(BitWidth);
1096 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001097 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001098 break;
1099 }
1100 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001101 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001102 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001103
1104 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1105 if (const VectorType *SrcVTy =
1106 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1107 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1108 // Don't touch a bitcast between vectors of different element counts.
1109 return false;
1110 } else
1111 // Don't touch a scalar-to-vector bitcast.
1112 return false;
1113 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1114 // Don't touch a vector-to-scalar bitcast.
1115 return false;
1116
Chris Lattner886ab6c2009-01-31 08:15:18 +00001117 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001118 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001119 return I;
1120 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001121 break;
1122 case Instruction::ZExt: {
1123 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001124 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001125
Zhou Shengd48653a2007-03-29 04:45:55 +00001126 DemandedMask.trunc(SrcBitWidth);
1127 RHSKnownZero.trunc(SrcBitWidth);
1128 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001129 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001130 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001131 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001132 DemandedMask.zext(BitWidth);
1133 RHSKnownZero.zext(BitWidth);
1134 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001135 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001136 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001137 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001138 break;
1139 }
1140 case Instruction::SExt: {
1141 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001142 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001143
Reid Spencer8cb68342007-03-12 17:25:59 +00001144 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001145 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001146
Zhou Sheng01542f32007-03-29 02:26:30 +00001147 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001148 // If any of the sign extended bits are demanded, we know that the sign
1149 // bit is demanded.
1150 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001151 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001152
Zhou Shengd48653a2007-03-29 04:45:55 +00001153 InputDemandedBits.trunc(SrcBitWidth);
1154 RHSKnownZero.trunc(SrcBitWidth);
1155 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001156 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001157 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001158 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001159 InputDemandedBits.zext(BitWidth);
1160 RHSKnownZero.zext(BitWidth);
1161 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001162 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001163
1164 // If the sign bit of the input is known set or clear, then we know the
1165 // top bits of the result.
1166
1167 // If the input sign bit is known zero, or if the NewBits are not demanded
1168 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001169 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001170 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001171 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1172 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001173 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001174 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001175 }
1176 break;
1177 }
1178 case Instruction::Add: {
1179 // Figure out what the input bits are. If the top bits of the and result
1180 // are not demanded, then the add doesn't demand them from its input
1181 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001182 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001183
1184 // If there is a constant on the RHS, there are a variety of xformations
1185 // we can do.
1186 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1187 // If null, this should be simplified elsewhere. Some of the xforms here
1188 // won't work if the RHS is zero.
1189 if (RHS->isZero())
1190 break;
1191
1192 // If the top bit of the output is demanded, demand everything from the
1193 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001194 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001195
1196 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001197 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001198 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001199 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001200
1201 // If the RHS of the add has bits set that can't affect the input, reduce
1202 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001203 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001204 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001205
1206 // Avoid excess work.
1207 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1208 break;
1209
1210 // Turn it into OR if input bits are zero.
1211 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1212 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001213 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001214 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001215 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001216 }
1217
1218 // We can say something about the output known-zero and known-one bits,
1219 // depending on potential carries from the input constant and the
1220 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1221 // bits set and the RHS constant is 0x01001, then we know we have a known
1222 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1223
1224 // To compute this, we first compute the potential carry bits. These are
1225 // the bits which may be modified. I'm not aware of a better way to do
1226 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001227 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001228 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001229
1230 // Now that we know which bits have carries, compute the known-1/0 sets.
1231
1232 // Bits are known one if they are known zero in one operand and one in the
1233 // other, and there is no input carry.
1234 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1235 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1236
1237 // Bits are known zero if they are known zero in both operands and there
1238 // is no input carry.
1239 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1240 } else {
1241 // If the high-bits of this ADD are not demanded, then it does not demand
1242 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001243 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001244 // Right fill the mask of bits for this ADD to demand the most
1245 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001246 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001247 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1248 LHSKnownZero, LHSKnownOne, Depth+1) ||
1249 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001250 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001251 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001252 }
1253 }
1254 break;
1255 }
1256 case Instruction::Sub:
1257 // If the high-bits of this SUB are not demanded, then it does not demand
1258 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001259 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001260 // Right fill the mask of bits for this SUB to demand the most
1261 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001262 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001263 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001264 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1265 LHSKnownZero, LHSKnownOne, Depth+1) ||
1266 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001267 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001268 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001269 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001270 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1271 // the known zeros and ones.
1272 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001273 break;
1274 case Instruction::Shl:
1275 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001276 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001277 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001278 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001279 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001280 return I;
1281 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001282 RHSKnownZero <<= ShiftAmt;
1283 RHSKnownOne <<= ShiftAmt;
1284 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001285 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001286 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001287 }
1288 break;
1289 case Instruction::LShr:
1290 // For a logical shift right
1291 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001292 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001293
Reid Spencer8cb68342007-03-12 17:25:59 +00001294 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001295 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001296 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001297 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001298 return I;
1299 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001300 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1301 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001302 if (ShiftAmt) {
1303 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001304 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001305 RHSKnownZero |= HighBits; // high bits known zero.
1306 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001307 }
1308 break;
1309 case Instruction::AShr:
1310 // If this is an arithmetic shift right and only the low-bit is set, we can
1311 // always convert this into a logical shr, even if the shift amount is
1312 // variable. The low bit of the shift cannot be an input sign bit unless
1313 // the shift amount is >= the size of the datatype, which is undefined.
1314 if (DemandedMask == 1) {
1315 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001316 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001317 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001318 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001319 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001320
1321 // If the sign bit is the only bit demanded by this ashr, then there is no
1322 // need to do it, the shift doesn't change the high bit.
1323 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001324 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001325
1326 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001327 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001328
Reid Spencer8cb68342007-03-12 17:25:59 +00001329 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001330 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001331 // If any of the "high bits" are demanded, we should set the sign bit as
1332 // demanded.
1333 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1334 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001335 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001336 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001337 return I;
1338 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001339 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001340 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001341 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1342 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1343
1344 // Handle the sign bits.
1345 APInt SignBit(APInt::getSignBit(BitWidth));
1346 // Adjust to where it is now in the mask.
1347 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1348
1349 // If the input sign bit is known to be zero, or if none of the top bits
1350 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001351 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001352 (HighBits & ~DemandedMask) == HighBits) {
1353 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001354 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001355 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001356 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001357 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1358 RHSKnownOne |= HighBits;
1359 }
1360 }
1361 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001362 case Instruction::SRem:
1363 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001364 APInt RA = Rem->getValue().abs();
1365 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001366 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001367 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001368
Nick Lewycky8e394322008-11-02 02:41:50 +00001369 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001370 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001371 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001372 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001373 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001374
1375 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1376 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001377
1378 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001379
Chris Lattner886ab6c2009-01-31 08:15:18 +00001380 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001381 }
1382 }
1383 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001384 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001385 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1386 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001387 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1388 KnownZero2, KnownOne2, Depth+1) ||
1389 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001390 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001391 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001392
Chris Lattner455e9ab2009-01-21 18:09:24 +00001393 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001394 Leaders = std::max(Leaders,
1395 KnownZero2.countLeadingOnes());
1396 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001397 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001398 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001399 case Instruction::Call:
1400 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1401 switch (II->getIntrinsicID()) {
1402 default: break;
1403 case Intrinsic::bswap: {
1404 // If the only bits demanded come from one byte of the bswap result,
1405 // just shift the input byte into position to eliminate the bswap.
1406 unsigned NLZ = DemandedMask.countLeadingZeros();
1407 unsigned NTZ = DemandedMask.countTrailingZeros();
1408
1409 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1410 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1411 // have 14 leading zeros, round to 8.
1412 NLZ &= ~7;
1413 NTZ &= ~7;
1414 // If we need exactly one byte, we can do this transformation.
1415 if (BitWidth-NLZ-NTZ == 8) {
1416 unsigned ResultBit = NTZ;
1417 unsigned InputBit = BitWidth-NTZ-8;
1418
1419 // Replace this with either a left or right shift to get the byte into
1420 // the right place.
1421 Instruction *NewVal;
1422 if (InputBit > ResultBit)
1423 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001424 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001425 else
1426 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001427 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001428 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001429 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001430 }
1431
1432 // TODO: Could compute known zero/one bits based on the input.
1433 break;
1434 }
1435 }
1436 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001437 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001438 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001439 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001440
1441 // If the client is only demanding bits that we know, return the known
1442 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001443 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1444 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001445 return false;
1446}
1447
Chris Lattner867b99f2006-10-05 06:55:50 +00001448
Mon P Wangaeb06d22008-11-10 04:46:22 +00001449/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001450/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001451/// actually used by the caller. This method analyzes which elements of the
1452/// operand are undef and returns that information in UndefElts.
1453///
1454/// If the information about demanded elements can be used to simplify the
1455/// operation, the operation is simplified, then the resultant value is
1456/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001457Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1458 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001459 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001460 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001461 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001462 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001463
1464 if (isa<UndefValue>(V)) {
1465 // If the entire vector is undefined, just return this info.
1466 UndefElts = EltMask;
1467 return 0;
1468 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1469 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001470 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001471 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001472
Chris Lattner867b99f2006-10-05 06:55:50 +00001473 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001474 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1475 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001476 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001477
1478 std::vector<Constant*> Elts;
1479 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001480 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001481 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001482 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001483 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1484 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001485 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001486 } else { // Otherwise, defined.
1487 Elts.push_back(CP->getOperand(i));
1488 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001489
Chris Lattner867b99f2006-10-05 06:55:50 +00001490 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001491 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001492 return NewCP != CP ? NewCP : 0;
1493 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001494 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001495 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001496
1497 // Check if this is identity. If so, return 0 since we are not simplifying
1498 // anything.
1499 if (DemandedElts == ((1ULL << VWidth) -1))
1500 return 0;
1501
Reid Spencer9d6565a2007-02-15 02:26:10 +00001502 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001503 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001504 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001505 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001506 for (unsigned i = 0; i != VWidth; ++i) {
1507 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1508 Elts.push_back(Elt);
1509 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001510 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001511 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001512 }
1513
Dan Gohman488fbfc2008-09-09 18:11:14 +00001514 // Limit search depth.
1515 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001516 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001517
1518 // If multiple users are using the root value, procede with
1519 // simplification conservatively assuming that all elements
1520 // are needed.
1521 if (!V->hasOneUse()) {
1522 // Quit if we find multiple users of a non-root value though.
1523 // They'll be handled when it's their turn to be visited by
1524 // the main instcombine process.
1525 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001526 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001527 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001528
1529 // Conservatively assume that all elements are needed.
1530 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001531 }
1532
1533 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001534 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001535
1536 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001537 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001538 Value *TmpV;
1539 switch (I->getOpcode()) {
1540 default: break;
1541
1542 case Instruction::InsertElement: {
1543 // If this is a variable index, we don't know which element it overwrites.
1544 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001545 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001546 if (Idx == 0) {
1547 // Note that we can't propagate undef elt info, because we don't know
1548 // which elt is getting updated.
1549 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1550 UndefElts2, Depth+1);
1551 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1552 break;
1553 }
1554
1555 // If this is inserting an element that isn't demanded, remove this
1556 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001557 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001558 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001559 return AddSoonDeadInstToWorklist(*I, 0);
1560
1561 // Otherwise, the element inserted overwrites whatever was there, so the
1562 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001563 APInt DemandedElts2 = DemandedElts;
1564 DemandedElts2.clear(IdxNo);
1565 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001566 UndefElts, Depth+1);
1567 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1568
1569 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001570 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001571 break;
1572 }
1573 case Instruction::ShuffleVector: {
1574 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001575 uint64_t LHSVWidth =
1576 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001577 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001578 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001579 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001580 unsigned MaskVal = Shuffle->getMaskValue(i);
1581 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001582 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001583 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001584 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001585 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001586 else
Evan Cheng388df622009-02-03 10:05:09 +00001587 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001588 }
1589 }
1590 }
1591
Nate Begeman7b254672009-02-11 22:36:25 +00001592 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001593 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001594 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001595 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1596
Nate Begeman7b254672009-02-11 22:36:25 +00001597 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001598 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1599 UndefElts3, Depth+1);
1600 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1601
1602 bool NewUndefElts = false;
1603 for (unsigned i = 0; i < VWidth; i++) {
1604 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001605 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001606 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001607 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001608 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001609 NewUndefElts = true;
1610 UndefElts.set(i);
1611 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001612 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001613 if (UndefElts3[MaskVal - LHSVWidth]) {
1614 NewUndefElts = true;
1615 UndefElts.set(i);
1616 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001617 }
1618 }
1619
1620 if (NewUndefElts) {
1621 // Add additional discovered undefs.
1622 std::vector<Constant*> Elts;
1623 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001624 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001625 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001626 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001627 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001628 Shuffle->getMaskValue(i)));
1629 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001630 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001631 MadeChange = true;
1632 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001633 break;
1634 }
Chris Lattner69878332007-04-14 22:29:23 +00001635 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001636 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001637 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1638 if (!VTy) break;
1639 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001640 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001641 unsigned Ratio;
1642
1643 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001644 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001645 // elements as are demanded of us.
1646 Ratio = 1;
1647 InputDemandedElts = DemandedElts;
1648 } else if (VWidth > InVWidth) {
1649 // Untested so far.
1650 break;
1651
1652 // If there are more elements in the result than there are in the source,
1653 // then an input element is live if any of the corresponding output
1654 // elements are live.
1655 Ratio = VWidth/InVWidth;
1656 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001657 if (DemandedElts[OutIdx])
1658 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001659 }
1660 } else {
1661 // Untested so far.
1662 break;
1663
1664 // If there are more elements in the source than there are in the result,
1665 // then an input element is live if the corresponding output element is
1666 // live.
1667 Ratio = InVWidth/VWidth;
1668 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001669 if (DemandedElts[InIdx/Ratio])
1670 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001671 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001672
Chris Lattner69878332007-04-14 22:29:23 +00001673 // div/rem demand all inputs, because they don't want divide by zero.
1674 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1675 UndefElts2, Depth+1);
1676 if (TmpV) {
1677 I->setOperand(0, TmpV);
1678 MadeChange = true;
1679 }
1680
1681 UndefElts = UndefElts2;
1682 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001683 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001684 // If there are more elements in the result than there are in the source,
1685 // then an output element is undef if the corresponding input element is
1686 // undef.
1687 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001688 if (UndefElts2[OutIdx/Ratio])
1689 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001690 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001691 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001692 // If there are more elements in the source than there are in the result,
1693 // then a result element is undef if all of the corresponding input
1694 // elements are undef.
1695 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1696 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001697 if (!UndefElts2[InIdx]) // Not undef?
1698 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001699 }
1700 break;
1701 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001702 case Instruction::And:
1703 case Instruction::Or:
1704 case Instruction::Xor:
1705 case Instruction::Add:
1706 case Instruction::Sub:
1707 case Instruction::Mul:
1708 // div/rem demand all inputs, because they don't want divide by zero.
1709 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1710 UndefElts, Depth+1);
1711 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1712 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1713 UndefElts2, Depth+1);
1714 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1715
1716 // Output elements are undefined if both are undefined. Consider things
1717 // like undef&0. The result is known zero, not undef.
1718 UndefElts &= UndefElts2;
1719 break;
1720
1721 case Instruction::Call: {
1722 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1723 if (!II) break;
1724 switch (II->getIntrinsicID()) {
1725 default: break;
1726
1727 // Binary vector operations that work column-wise. A dest element is a
1728 // function of the corresponding input elements from the two inputs.
1729 case Intrinsic::x86_sse_sub_ss:
1730 case Intrinsic::x86_sse_mul_ss:
1731 case Intrinsic::x86_sse_min_ss:
1732 case Intrinsic::x86_sse_max_ss:
1733 case Intrinsic::x86_sse2_sub_sd:
1734 case Intrinsic::x86_sse2_mul_sd:
1735 case Intrinsic::x86_sse2_min_sd:
1736 case Intrinsic::x86_sse2_max_sd:
1737 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1738 UndefElts, Depth+1);
1739 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1740 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1741 UndefElts2, Depth+1);
1742 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1743
1744 // If only the low elt is demanded and this is a scalarizable intrinsic,
1745 // scalarize it now.
1746 if (DemandedElts == 1) {
1747 switch (II->getIntrinsicID()) {
1748 default: break;
1749 case Intrinsic::x86_sse_sub_ss:
1750 case Intrinsic::x86_sse_mul_ss:
1751 case Intrinsic::x86_sse2_sub_sd:
1752 case Intrinsic::x86_sse2_mul_sd:
1753 // TODO: Lower MIN/MAX/ABS/etc
1754 Value *LHS = II->getOperand(1);
1755 Value *RHS = II->getOperand(2);
1756 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001757 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001758 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001759 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001760 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001761
1762 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001763 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001764 case Intrinsic::x86_sse_sub_ss:
1765 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001766 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001767 II->getName()), *II);
1768 break;
1769 case Intrinsic::x86_sse_mul_ss:
1770 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001771 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001772 II->getName()), *II);
1773 break;
1774 }
1775
1776 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001777 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001778 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001779 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001780 InsertNewInstBefore(New, *II);
1781 AddSoonDeadInstToWorklist(*II, 0);
1782 return New;
1783 }
1784 }
1785
1786 // Output elements are undefined if both are undefined. Consider things
1787 // like undef&0. The result is known zero, not undef.
1788 UndefElts &= UndefElts2;
1789 break;
1790 }
1791 break;
1792 }
1793 }
1794 return MadeChange ? I : 0;
1795}
1796
Dan Gohman45b4e482008-05-19 22:14:15 +00001797
Chris Lattner564a7272003-08-13 19:01:45 +00001798/// AssociativeOpt - Perform an optimization on an associative operator. This
1799/// function is designed to check a chain of associative operators for a
1800/// potential to apply a certain optimization. Since the optimization may be
1801/// applicable if the expression was reassociated, this checks the chain, then
1802/// reassociates the expression as necessary to expose the optimization
1803/// opportunity. This makes use of a special Functor, which must define
1804/// 'shouldApply' and 'apply' methods.
1805///
1806template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001807static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001808 unsigned Opcode = Root.getOpcode();
1809 Value *LHS = Root.getOperand(0);
1810
1811 // Quick check, see if the immediate LHS matches...
1812 if (F.shouldApply(LHS))
1813 return F.apply(Root);
1814
1815 // Otherwise, if the LHS is not of the same opcode as the root, return.
1816 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001817 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001818 // Should we apply this transform to the RHS?
1819 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1820
1821 // If not to the RHS, check to see if we should apply to the LHS...
1822 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1823 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1824 ShouldApply = true;
1825 }
1826
1827 // If the functor wants to apply the optimization to the RHS of LHSI,
1828 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1829 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001830 // Now all of the instructions are in the current basic block, go ahead
1831 // and perform the reassociation.
1832 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1833
1834 // First move the selected RHS to the LHS of the root...
1835 Root.setOperand(0, LHSI->getOperand(1));
1836
1837 // Make what used to be the LHS of the root be the user of the root...
1838 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001839 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001840 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001841 return 0;
1842 }
Chris Lattner65725312004-04-16 18:08:07 +00001843 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001844 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001845 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001846 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001847 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001848
1849 // Now propagate the ExtraOperand down the chain of instructions until we
1850 // get to LHSI.
1851 while (TmpLHSI != LHSI) {
1852 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001853 // Move the instruction to immediately before the chain we are
1854 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001855 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001856 ARI = NextLHSI;
1857
Chris Lattner564a7272003-08-13 19:01:45 +00001858 Value *NextOp = NextLHSI->getOperand(1);
1859 NextLHSI->setOperand(1, ExtraOperand);
1860 TmpLHSI = NextLHSI;
1861 ExtraOperand = NextOp;
1862 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001863
Chris Lattner564a7272003-08-13 19:01:45 +00001864 // Now that the instructions are reassociated, have the functor perform
1865 // the transformation...
1866 return F.apply(Root);
1867 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001868
Chris Lattner564a7272003-08-13 19:01:45 +00001869 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1870 }
1871 return 0;
1872}
1873
Dan Gohman844731a2008-05-13 00:00:25 +00001874namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001875
Nick Lewycky02d639f2008-05-23 04:34:58 +00001876// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001877struct AddRHS {
1878 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001879 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001880 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1881 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001882 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001883 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001884 }
1885};
1886
1887// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1888// iff C1&C2 == 0
1889struct AddMaskingAnd {
1890 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001891 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001892 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001893 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001894 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001895 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001896 }
1897 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001898 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001899 }
1900};
1901
Dan Gohman844731a2008-05-13 00:00:25 +00001902}
1903
Chris Lattner6e7ba452005-01-01 16:22:27 +00001904static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001905 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001906 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001907 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001908 }
1909
Chris Lattner2eefe512004-04-09 19:05:30 +00001910 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001911 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1912 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001913
Chris Lattner2eefe512004-04-09 19:05:30 +00001914 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1915 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001916 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1917 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001918 }
1919
1920 Value *Op0 = SO, *Op1 = ConstOperand;
1921 if (!ConstIsRHS)
1922 std::swap(Op0, Op1);
1923 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001924 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001925 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001926 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001927 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +00001928 Op0, Op1, SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001929 else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001930 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001931 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001932 return IC->InsertNewInstBefore(New, I);
1933}
1934
1935// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1936// constant as the other operand, try to fold the binary operator into the
1937// select arguments. This also works for Cast instructions, which obviously do
1938// not have a second operand.
1939static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1940 InstCombiner *IC) {
1941 // Don't modify shared select instructions
1942 if (!SI->hasOneUse()) return 0;
1943 Value *TV = SI->getOperand(1);
1944 Value *FV = SI->getOperand(2);
1945
1946 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001947 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00001948 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001949
Chris Lattner6e7ba452005-01-01 16:22:27 +00001950 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1951 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1952
Gabor Greif051a9502008-04-06 20:25:17 +00001953 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1954 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001955 }
1956 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001957}
1958
Chris Lattner4e998b22004-09-29 05:07:12 +00001959
1960/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1961/// node as operand #0, see if we can fold the instruction into the PHI (which
1962/// is only possible if all operands to the PHI are constants).
1963Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1964 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001965 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001966 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001967
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001968 // Check to see if all of the operands of the PHI are constants. If there is
1969 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001970 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001971 BasicBlock *NonConstBB = 0;
1972 for (unsigned i = 0; i != NumPHIValues; ++i)
1973 if (!isa<Constant>(PN->getIncomingValue(i))) {
1974 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001975 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001976 NonConstBB = PN->getIncomingBlock(i);
1977
1978 // If the incoming non-constant value is in I's block, we have an infinite
1979 // loop.
1980 if (NonConstBB == I.getParent())
1981 return 0;
1982 }
1983
1984 // If there is exactly one non-constant value, we can insert a copy of the
1985 // operation in that block. However, if this is a critical edge, we would be
1986 // inserting the computation one some other paths (e.g. inside a loop). Only
1987 // do this if the pred block is unconditionally branching into the phi block.
1988 if (NonConstBB) {
1989 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1990 if (!BI || !BI->isUnconditional()) return 0;
1991 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001992
1993 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001994 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001995 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001996 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001997 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001998
1999 // Next, add all of the operands to the PHI.
2000 if (I.getNumOperands() == 2) {
2001 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002002 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002003 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002004 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002005 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002006 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002007 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002008 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002009 } else {
2010 assert(PN->getIncomingBlock(i) == NonConstBB);
2011 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002012 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002013 PN->getIncomingValue(i), C, "phitmp",
2014 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002015 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002016 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002017 CI->getPredicate(),
2018 PN->getIncomingValue(i), C, "phitmp",
2019 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002020 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002021 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002022
Chris Lattnerdbab3862007-03-02 21:28:56 +00002023 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002024 }
2025 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002026 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002027 } else {
2028 CastInst *CI = cast<CastInst>(&I);
2029 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002030 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002031 Value *InV;
2032 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002033 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002034 } else {
2035 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002036 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002037 I.getType(), "phitmp",
2038 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002039 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002040 }
2041 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002042 }
2043 }
2044 return ReplaceInstUsesWith(I, NewPN);
2045}
2046
Chris Lattner2454a2e2008-01-29 06:52:45 +00002047
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002048/// WillNotOverflowSignedAdd - Return true if we can prove that:
2049/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2050/// This basically requires proving that the add in the original type would not
2051/// overflow to change the sign bit or have a carry out.
2052bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2053 // There are different heuristics we can use for this. Here are some simple
2054 // ones.
2055
2056 // Add has the property that adding any two 2's complement numbers can only
2057 // have one carry bit which can change a sign. As such, if LHS and RHS each
2058 // have at least two sign bits, we know that the addition of the two values will
2059 // sign extend fine.
2060 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2061 return true;
2062
2063
2064 // If one of the operands only has one non-zero bit, and if the other operand
2065 // has a known-zero bit in a more significant place than it (not including the
2066 // sign bit) the ripple may go up to and fill the zero, but won't change the
2067 // sign. For example, (X & ~4) + 1.
2068
2069 // TODO: Implement.
2070
2071 return false;
2072}
2073
Chris Lattner2454a2e2008-01-29 06:52:45 +00002074
Chris Lattner7e708292002-06-25 16:13:24 +00002075Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002076 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002077 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002078
Chris Lattner66331a42004-04-10 22:01:55 +00002079 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002080 // X + undef -> undef
2081 if (isa<UndefValue>(RHS))
2082 return ReplaceInstUsesWith(I, RHS);
2083
Chris Lattner66331a42004-04-10 22:01:55 +00002084 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002085 if (RHSC->isNullValue())
2086 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002087
Chris Lattner66331a42004-04-10 22:01:55 +00002088 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002089 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002090 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002091 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002092 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002093 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002094
2095 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2096 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002097 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002098 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002099
Eli Friedman709b33d2009-07-13 22:27:52 +00002100 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002101 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002102 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002103 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002104 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002105
2106 if (isa<PHINode>(LHS))
2107 if (Instruction *NV = FoldOpIntoPhi(I))
2108 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002109
Chris Lattner4f637d42006-01-06 17:59:59 +00002110 ConstantInt *XorRHS = 0;
2111 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002112 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002113 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002114 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002115 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002116
Zhou Sheng4351c642007-04-02 08:20:41 +00002117 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002118 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2119 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002120 do {
2121 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002122 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2123 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002124 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2125 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002126 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002127 if (!MaskedValueIsZero(XorLHS,
2128 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002129 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002130 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002131 }
2132 }
2133 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002134 C0080Val = APIntOps::lshr(C0080Val, Size);
2135 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2136 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002137
Reid Spencer35c38852007-03-28 01:36:16 +00002138 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002139 // with funny bit widths then this switch statement should be removed. It
2140 // is just here to get the size of the "middle" type back up to something
2141 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002142 const Type *MiddleType = 0;
2143 switch (Size) {
2144 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002145 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2146 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2147 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002148 }
2149 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002150 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002151 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002152 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002153 }
2154 }
Chris Lattner66331a42004-04-10 22:01:55 +00002155 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002156
Owen Anderson1d0be152009-08-13 21:58:54 +00002157 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002158 return BinaryOperator::CreateXor(LHS, RHS);
2159
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002160 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002161 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002162 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002163 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002164
2165 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2166 if (RHSI->getOpcode() == Instruction::Sub)
2167 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2168 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2169 }
2170 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2171 if (LHSI->getOpcode() == Instruction::Sub)
2172 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2173 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2174 }
Robert Bocchino71698282004-07-27 21:02:21 +00002175 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002176
Chris Lattner5c4afb92002-05-08 22:46:53 +00002177 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002178 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002179 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002180 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002181 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002182 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002183 InsertNewInstBefore(NewAdd, I);
Dan Gohman4ae51262009-08-12 16:23:25 +00002184 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002185 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002186 }
2187
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002188 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002189 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002190
2191 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002192 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002193 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002194 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002195
Misha Brukmanfd939082005-04-21 23:48:37 +00002196
Chris Lattner50af16a2004-11-13 19:50:12 +00002197 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002198 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002199 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002200 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002201
2202 // X*C1 + X*C2 --> X * (C1+C2)
2203 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002204 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002205 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002206 }
2207
2208 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002209 if (dyn_castFoldableMul(RHS, C2) == LHS)
2210 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002211
Chris Lattnere617c9e2007-01-05 02:17:46 +00002212 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002213 if (dyn_castNotVal(LHS) == RHS ||
2214 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002215 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002216
Chris Lattnerad3448c2003-02-18 19:57:07 +00002217
Chris Lattner564a7272003-08-13 19:01:45 +00002218 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002219 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2220 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002221 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002222
2223 // A+B --> A|B iff A and B have no bits set in common.
2224 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2225 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2226 APInt LHSKnownOne(IT->getBitWidth(), 0);
2227 APInt LHSKnownZero(IT->getBitWidth(), 0);
2228 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2229 if (LHSKnownZero != 0) {
2230 APInt RHSKnownOne(IT->getBitWidth(), 0);
2231 APInt RHSKnownZero(IT->getBitWidth(), 0);
2232 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2233
2234 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002235 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002236 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002237 }
2238 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002239
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002240 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002241 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002242 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002243 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2244 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002245 if (W != Y) {
2246 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002247 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002248 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002249 std::swap(W, X);
2250 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002251 std::swap(Y, Z);
2252 std::swap(W, X);
2253 }
2254 }
2255
2256 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002257 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002258 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002259 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002260 }
2261 }
2262 }
2263
Chris Lattner6b032052003-10-02 15:11:26 +00002264 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002265 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002266 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002267 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002268
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002269 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002270 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002271 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002272 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002273 if (Anded == CRHS) {
2274 // See if all bits from the first bit set in the Add RHS up are included
2275 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002276 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002277
2278 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002279 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002280
2281 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002282 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002283
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002284 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2285 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002286 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002287 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002288 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002289 }
2290 }
2291 }
2292
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002293 // Try to fold constant add into select arguments.
2294 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002295 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002296 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002297 }
2298
Chris Lattner42790482007-12-20 01:56:58 +00002299 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002300 {
2301 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002302 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002303 if (!SI) {
2304 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002305 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002306 }
Chris Lattner42790482007-12-20 01:56:58 +00002307 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002308 Value *TV = SI->getTrueValue();
2309 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002310 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002311
2312 // Can we fold the add into the argument of the select?
2313 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002314 if (match(FV, m_Zero()) &&
2315 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002316 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002317 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002318 if (match(TV, m_Zero()) &&
2319 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002320 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002321 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002322 }
2323 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002324
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002325 // Check for (add (sext x), y), see if we can merge this into an
2326 // integer add followed by a sext.
2327 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2328 // (add (sext x), cst) --> (sext (add x, cst'))
2329 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2330 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002331 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002332 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002333 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002334 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2335 // Insert the new, smaller add.
2336 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2337 CI, "addconv");
2338 InsertNewInstBefore(NewAdd, I);
2339 return new SExtInst(NewAdd, I.getType());
2340 }
2341 }
2342
2343 // (add (sext x), (sext y)) --> (sext (add int x, y))
2344 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2345 // Only do this if x/y have the same type, if at last one of them has a
2346 // single use (so we don't increase the number of sexts), and if the
2347 // integer add will not overflow.
2348 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2349 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2350 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2351 RHSConv->getOperand(0))) {
2352 // Insert the new integer add.
2353 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2354 RHSConv->getOperand(0),
2355 "addconv");
2356 InsertNewInstBefore(NewAdd, I);
2357 return new SExtInst(NewAdd, I.getType());
2358 }
2359 }
2360 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002361
2362 return Changed ? &I : 0;
2363}
2364
2365Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2366 bool Changed = SimplifyCommutative(I);
2367 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2368
2369 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2370 // X + 0 --> X
2371 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002372 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002373 (I.getType())->getValueAPF()))
2374 return ReplaceInstUsesWith(I, LHS);
2375 }
2376
2377 if (isa<PHINode>(LHS))
2378 if (Instruction *NV = FoldOpIntoPhi(I))
2379 return NV;
2380 }
2381
2382 // -A + B --> B - A
2383 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002384 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002385 return BinaryOperator::CreateFSub(RHS, LHSV);
2386
2387 // A + -B --> A - B
2388 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002389 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002390 return BinaryOperator::CreateFSub(LHS, V);
2391
2392 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2393 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2394 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2395 return ReplaceInstUsesWith(I, LHS);
2396
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002397 // Check for (add double (sitofp x), y), see if we can merge this into an
2398 // integer add followed by a promotion.
2399 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2400 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2401 // ... if the constant fits in the integer value. This is useful for things
2402 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2403 // requires a constant pool load, and generally allows the add to be better
2404 // instcombined.
2405 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2406 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002407 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002408 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002409 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002410 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2411 // Insert the new integer add.
2412 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2413 CI, "addconv");
2414 InsertNewInstBefore(NewAdd, I);
2415 return new SIToFPInst(NewAdd, I.getType());
2416 }
2417 }
2418
2419 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2420 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2421 // Only do this if x/y have the same type, if at last one of them has a
2422 // single use (so we don't increase the number of int->fp conversions),
2423 // and if the integer add will not overflow.
2424 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2425 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2426 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2427 RHSConv->getOperand(0))) {
2428 // Insert the new integer add.
2429 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2430 RHSConv->getOperand(0),
2431 "addconv");
2432 InsertNewInstBefore(NewAdd, I);
2433 return new SIToFPInst(NewAdd, I.getType());
2434 }
2435 }
2436 }
2437
Chris Lattner7e708292002-06-25 16:13:24 +00002438 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002439}
2440
Chris Lattner7e708292002-06-25 16:13:24 +00002441Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002442 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002443
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002444 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002445 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002446
Chris Lattner233f7dc2002-08-12 21:17:25 +00002447 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002448 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002449 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002450
Chris Lattnere87597f2004-10-16 18:11:37 +00002451 if (isa<UndefValue>(Op0))
2452 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2453 if (isa<UndefValue>(Op1))
2454 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2455
Chris Lattnerd65460f2003-11-05 01:06:05 +00002456 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2457 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002458 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002459 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002460
Chris Lattnerd65460f2003-11-05 01:06:05 +00002461 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002462 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002463 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002464 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002465
Chris Lattner76b7a062007-01-15 07:02:54 +00002466 // -(X >>u 31) -> (X >>s 31)
2467 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002468 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002469 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002470 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002471 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002472 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002473 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002474 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002475 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002476 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002477 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002478 }
2479 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002480 }
2481 else if (SI->getOpcode() == Instruction::AShr) {
2482 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2483 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002484 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002485 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002486 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002487 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002488 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002489 }
2490 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002491 }
2492 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002493 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002494
2495 // Try to fold constant sub into select arguments.
2496 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002497 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002498 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002499
2500 // C - zext(bool) -> bool ? C - 1 : C
2501 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002502 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002503 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002504 }
2505
Owen Anderson1d0be152009-08-13 21:58:54 +00002506 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002507 return BinaryOperator::CreateXor(Op0, Op1);
2508
Chris Lattner43d84d62005-04-07 16:15:25 +00002509 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002510 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002511 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002512 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002513 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002514 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002515 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002516 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002517 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2518 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2519 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002520 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002521 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002522 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002523 }
2524
Chris Lattnerfd059242003-10-15 16:48:29 +00002525 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002526 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2527 // is not used by anyone else...
2528 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002529 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002530 // Swap the two operands of the subexpr...
2531 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2532 Op1I->setOperand(0, IIOp1);
2533 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002534
Chris Lattnera2881962003-02-18 19:28:33 +00002535 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002536 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002537 }
2538
2539 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2540 //
2541 if (Op1I->getOpcode() == Instruction::And &&
2542 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2543 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2544
Chris Lattnerf523d062004-06-09 05:08:07 +00002545 Value *NewNot =
Dan Gohman4ae51262009-08-12 16:23:25 +00002546 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002547 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002548 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002549
Reid Spencerac5209e2006-10-16 23:08:08 +00002550 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002551 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002552 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002553 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002554 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002555 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002556 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002557
Chris Lattnerad3448c2003-02-18 19:57:07 +00002558 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002559 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002560 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002561 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002562 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002563 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002564 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002565 }
Chris Lattner40371712002-05-09 01:29:19 +00002566 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002567 }
Chris Lattnera2881962003-02-18 19:28:33 +00002568
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002569 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2570 if (Op0I->getOpcode() == Instruction::Add) {
2571 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2572 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2573 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2574 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2575 } else if (Op0I->getOpcode() == Instruction::Sub) {
2576 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002577 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002578 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002579 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002580 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002581
Chris Lattner50af16a2004-11-13 19:50:12 +00002582 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002583 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002584 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002585 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002586
Chris Lattner50af16a2004-11-13 19:50:12 +00002587 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002588 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002589 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002590 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002591 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002592}
2593
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002594Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2595 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2596
2597 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002598 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002599 return BinaryOperator::CreateFAdd(Op0, V);
2600
2601 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2602 if (Op1I->getOpcode() == Instruction::FAdd) {
2603 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002604 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002605 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002606 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002607 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002608 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002609 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002610 }
2611
2612 return 0;
2613}
2614
Chris Lattnera0141b92007-07-15 20:42:37 +00002615/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2616/// comparison only checks the sign bit. If it only checks the sign bit, set
2617/// TrueIfSigned if the result of the comparison is true when the input value is
2618/// signed.
2619static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2620 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002621 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002622 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2623 TrueIfSigned = true;
2624 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002625 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2626 TrueIfSigned = true;
2627 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002628 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2629 TrueIfSigned = false;
2630 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002631 case ICmpInst::ICMP_UGT:
2632 // True if LHS u> RHS and RHS == high-bit-mask - 1
2633 TrueIfSigned = true;
2634 return RHS->getValue() ==
2635 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2636 case ICmpInst::ICMP_UGE:
2637 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2638 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002639 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002640 default:
2641 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002642 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002643}
2644
Chris Lattner7e708292002-06-25 16:13:24 +00002645Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002646 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002647 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002648
Eli Friedman1694e092009-07-18 09:12:15 +00002649 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002650 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002651
Chris Lattner233f7dc2002-08-12 21:17:25 +00002652 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002653 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2654 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002655
2656 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002657 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002658 if (SI->getOpcode() == Instruction::Shl)
2659 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002660 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002661 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002662
Zhou Sheng843f07672007-04-19 05:39:12 +00002663 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002664 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2665 if (CI->equalsInt(1)) // X * 1 == X
2666 return ReplaceInstUsesWith(I, Op0);
2667 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002668 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002669
Zhou Sheng97b52c22007-03-29 01:57:21 +00002670 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002671 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002672 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002673 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002674 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002675 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002676 if (Op1->isNullValue())
2677 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002678
2679 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2680 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002681 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002682
2683 // As above, vector X*splat(1.0) -> X in all defined cases.
2684 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002685 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2686 if (CI->equalsInt(1))
2687 return ReplaceInstUsesWith(I, Op0);
2688 }
2689 }
Chris Lattnera2881962003-02-18 19:28:33 +00002690 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002691
2692 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2693 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002694 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002695 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002696 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002697 Op1, "tmp");
2698 InsertNewInstBefore(Add, I);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002699 Value *C1C2 = ConstantExpr::getMul(Op1,
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002700 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002701 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002702
2703 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002704
2705 // Try to fold constant mul into select arguments.
2706 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002707 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002708 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002709
2710 if (isa<PHINode>(Op0))
2711 if (Instruction *NV = FoldOpIntoPhi(I))
2712 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002713 }
2714
Dan Gohman186a6362009-08-12 16:04:34 +00002715 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2716 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002717 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002718
Nick Lewycky0c730792008-11-21 07:33:58 +00002719 // (X / Y) * Y = X - (X % Y)
2720 // (X / Y) * -Y = (X % Y) - X
2721 {
2722 Value *Op1 = I.getOperand(1);
2723 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2724 if (!BO ||
2725 (BO->getOpcode() != Instruction::UDiv &&
2726 BO->getOpcode() != Instruction::SDiv)) {
2727 Op1 = Op0;
2728 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2729 }
Dan Gohman186a6362009-08-12 16:04:34 +00002730 Value *Neg = dyn_castNegVal(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002731 if (BO && BO->hasOneUse() &&
2732 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2733 (BO->getOpcode() == Instruction::UDiv ||
2734 BO->getOpcode() == Instruction::SDiv)) {
2735 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2736
Dan Gohmanfa94b942009-08-12 16:33:09 +00002737 // If the division is exact, X % Y is zero.
2738 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2739 if (SDiv->isExact()) {
2740 if (Op1BO == Op1)
2741 return ReplaceInstUsesWith(I, Op0BO);
2742 else
2743 return BinaryOperator::CreateNeg(Op0BO);
2744 }
2745
Nick Lewycky0c730792008-11-21 07:33:58 +00002746 Instruction *Rem;
2747 if (BO->getOpcode() == Instruction::UDiv)
2748 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2749 else
2750 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2751
2752 InsertNewInstBefore(Rem, I);
2753 Rem->takeName(BO);
2754
2755 if (Op1BO == Op1)
2756 return BinaryOperator::CreateSub(Op0BO, Rem);
2757 else
2758 return BinaryOperator::CreateSub(Rem, Op0BO);
2759 }
2760 }
2761
Owen Anderson1d0be152009-08-13 21:58:54 +00002762 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002763 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2764
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002765 // If one of the operands of the multiply is a cast from a boolean value, then
2766 // we know the bool is either zero or one, so this is a 'masking' multiply.
2767 // See if we can simplify things based on how the boolean was originally
2768 // formed.
2769 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002770 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Owen Anderson1d0be152009-08-13 21:58:54 +00002771 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002772 BoolCast = CI;
2773 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002774 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00002775 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002776 BoolCast = CI;
2777 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002778 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002779 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2780 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002781 bool TIS = false;
2782
Reid Spencere4d87aa2006-12-23 06:05:41 +00002783 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002784 // multiply into a shift/and combination.
2785 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002786 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2787 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002788 // Shift the X value right to turn it into "all signbits".
Owen Andersoneed707b2009-07-24 23:12:02 +00002789 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002790 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002791 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002792 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002793 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002794 BoolCast->getOperand(0)->getName()+
2795 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002796
2797 // If the multiply type is not the same as the source type, sign extend
2798 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002799 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002800 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2801 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002802 Instruction::CastOps opcode =
2803 (SrcBits == DstBits ? Instruction::BitCast :
2804 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2805 V = InsertCastBefore(opcode, V, I.getType(), I);
2806 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002807
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002808 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002809 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002810 }
2811 }
2812 }
2813
Chris Lattner7e708292002-06-25 16:13:24 +00002814 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002815}
2816
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002817Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2818 bool Changed = SimplifyCommutative(I);
2819 Value *Op0 = I.getOperand(0);
2820
2821 // Simplify mul instructions with a constant RHS...
2822 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2823 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2824 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2825 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2826 if (Op1F->isExactlyValue(1.0))
2827 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2828 } else if (isa<VectorType>(Op1->getType())) {
2829 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2830 // As above, vector X*splat(1.0) -> X in all defined cases.
2831 if (Constant *Splat = Op1V->getSplatValue()) {
2832 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2833 if (F->isExactlyValue(1.0))
2834 return ReplaceInstUsesWith(I, Op0);
2835 }
2836 }
2837 }
2838
2839 // Try to fold constant mul into select arguments.
2840 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2841 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2842 return R;
2843
2844 if (isa<PHINode>(Op0))
2845 if (Instruction *NV = FoldOpIntoPhi(I))
2846 return NV;
2847 }
2848
Dan Gohman186a6362009-08-12 16:04:34 +00002849 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2850 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002851 return BinaryOperator::CreateFMul(Op0v, Op1v);
2852
2853 return Changed ? &I : 0;
2854}
2855
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002856/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2857/// instruction.
2858bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2859 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2860
2861 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2862 int NonNullOperand = -1;
2863 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2864 if (ST->isNullValue())
2865 NonNullOperand = 2;
2866 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2867 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2868 if (ST->isNullValue())
2869 NonNullOperand = 1;
2870
2871 if (NonNullOperand == -1)
2872 return false;
2873
2874 Value *SelectCond = SI->getOperand(0);
2875
2876 // Change the div/rem to use 'Y' instead of the select.
2877 I.setOperand(1, SI->getOperand(NonNullOperand));
2878
2879 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2880 // problem. However, the select, or the condition of the select may have
2881 // multiple uses. Based on our knowledge that the operand must be non-zero,
2882 // propagate the known value for the select into other uses of it, and
2883 // propagate a known value of the condition into its other users.
2884
2885 // If the select and condition only have a single use, don't bother with this,
2886 // early exit.
2887 if (SI->use_empty() && SelectCond->hasOneUse())
2888 return true;
2889
2890 // Scan the current block backward, looking for other uses of SI.
2891 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2892
2893 while (BBI != BBFront) {
2894 --BBI;
2895 // If we found a call to a function, we can't assume it will return, so
2896 // information from below it cannot be propagated above it.
2897 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2898 break;
2899
2900 // Replace uses of the select or its condition with the known values.
2901 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2902 I != E; ++I) {
2903 if (*I == SI) {
2904 *I = SI->getOperand(NonNullOperand);
2905 AddToWorkList(BBI);
2906 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002907 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2908 ConstantInt::getFalse(*Context);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002909 AddToWorkList(BBI);
2910 }
2911 }
2912
2913 // If we past the instruction, quit looking for it.
2914 if (&*BBI == SI)
2915 SI = 0;
2916 if (&*BBI == SelectCond)
2917 SelectCond = 0;
2918
2919 // If we ran out of things to eliminate, break out of the loop.
2920 if (SelectCond == 0 && SI == 0)
2921 break;
2922
2923 }
2924 return true;
2925}
2926
2927
Reid Spencer1628cec2006-10-26 06:15:43 +00002928/// This function implements the transforms on div instructions that work
2929/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2930/// used by the visitors to those instructions.
2931/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002932Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002933 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002934
Chris Lattner50b2ca42008-02-19 06:12:18 +00002935 // undef / X -> 0 for integer.
2936 // undef / X -> undef for FP (the undef could be a snan).
2937 if (isa<UndefValue>(Op0)) {
2938 if (Op0->getType()->isFPOrFPVector())
2939 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002940 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002941 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002942
2943 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002944 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002945 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002946
Reid Spencer1628cec2006-10-26 06:15:43 +00002947 return 0;
2948}
Misha Brukmanfd939082005-04-21 23:48:37 +00002949
Reid Spencer1628cec2006-10-26 06:15:43 +00002950/// This function implements the transforms common to both integer division
2951/// instructions (udiv and sdiv). It is called by the visitors to those integer
2952/// division instructions.
2953/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002954Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002955 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2956
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002957 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002958 if (Op0 == Op1) {
2959 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002960 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002961 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00002962 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002963 }
2964
Owen Andersoneed707b2009-07-24 23:12:02 +00002965 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002966 return ReplaceInstUsesWith(I, CI);
2967 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002968
Reid Spencer1628cec2006-10-26 06:15:43 +00002969 if (Instruction *Common = commonDivTransforms(I))
2970 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002971
2972 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2973 // This does not apply for fdiv.
2974 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2975 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002976
2977 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2978 // div X, 1 == X
2979 if (RHS->equalsInt(1))
2980 return ReplaceInstUsesWith(I, Op0);
2981
2982 // (X / C1) / C2 -> X / (C1*C2)
2983 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2984 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2985 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002986 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00002987 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00002988 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002989 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002990 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002991 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002992 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002993
Reid Spencerbca0e382007-03-23 20:05:17 +00002994 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002995 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2996 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2997 return R;
2998 if (isa<PHINode>(Op0))
2999 if (Instruction *NV = FoldOpIntoPhi(I))
3000 return NV;
3001 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003002 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003003
Chris Lattnera2881962003-02-18 19:28:33 +00003004 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003005 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003006 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003007 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003008
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003009 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003010 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003011 return ReplaceInstUsesWith(I, Op0);
3012
Nick Lewycky895f0852008-11-27 20:21:08 +00003013 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3014 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3015 // div X, 1 == X
3016 if (X->isOne())
3017 return ReplaceInstUsesWith(I, Op0);
3018 }
3019
Reid Spencer1628cec2006-10-26 06:15:43 +00003020 return 0;
3021}
3022
3023Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3024 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3025
3026 // Handle the integer div common cases
3027 if (Instruction *Common = commonIDivTransforms(I))
3028 return Common;
3029
Reid Spencer1628cec2006-10-26 06:15:43 +00003030 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003031 // X udiv C^2 -> X >> C
3032 // Check to see if this is an unsigned division with an exact power of 2,
3033 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003034 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003035 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003036 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003037
3038 // X udiv C, where C >= signbit
3039 if (C->getValue().isNegative()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003040 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky8ca52482008-11-27 22:41:10 +00003041 I);
Owen Andersona7235ea2009-07-31 20:28:14 +00003042 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003043 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003044 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003045 }
3046
3047 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003048 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003049 if (RHSI->getOpcode() == Instruction::Shl &&
3050 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003051 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003052 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003053 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003054 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003055 if (uint32_t C2 = C1.logBase2()) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003056 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003057 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003058 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003059 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003060 }
3061 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003062 }
3063
Reid Spencer1628cec2006-10-26 06:15:43 +00003064 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3065 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003066 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003067 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003068 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003069 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003070 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003071 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003072 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003073 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003074 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003075 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003076 Op0, TC, SI->getName()+".t");
3077 TSI = InsertNewInstBefore(TSI, I);
3078
3079 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003080 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003081 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003082 Op0, FC, SI->getName()+".f");
3083 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003084
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003085 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003086 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003087 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003088 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003089 return 0;
3090}
3091
Reid Spencer1628cec2006-10-26 06:15:43 +00003092Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3093 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3094
3095 // Handle the integer div common cases
3096 if (Instruction *Common = commonIDivTransforms(I))
3097 return Common;
3098
3099 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3100 // sdiv X, -1 == -X
3101 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003102 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003103
Dan Gohmanfa94b942009-08-12 16:33:09 +00003104 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003105 if (cast<SDivOperator>(&I)->isExact() &&
3106 RHS->getValue().isNonNegative() &&
3107 RHS->getValue().isPowerOf2()) {
3108 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3109 RHS->getValue().exactLogBase2());
3110 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3111 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003112
3113 // -X/C --> X/-C provided the negation doesn't overflow.
3114 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3115 if (isa<Constant>(Sub->getOperand(0)) &&
3116 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003117 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003118 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3119 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003120 }
3121
3122 // If the sign bits of both operands are zero (i.e. we can prove they are
3123 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003124 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003125 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003126 if (MaskedValueIsZero(Op0, Mask)) {
3127 if (MaskedValueIsZero(Op1, Mask)) {
3128 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3129 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3130 }
3131 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003132 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003133 ShiftedInt->getValue().isPowerOf2()) {
3134 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3135 // Safe because the only negative value (1 << Y) can take on is
3136 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3137 // the sign bit set.
3138 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3139 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003140 }
Eli Friedman8be17392009-07-18 09:53:21 +00003141 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003142
3143 return 0;
3144}
3145
3146Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3147 return commonDivTransforms(I);
3148}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003149
Reid Spencer0a783f72006-11-02 01:53:59 +00003150/// This function implements the transforms on rem instructions that work
3151/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3152/// is used by the visitors to those instructions.
3153/// @brief Transforms common to all three rem instructions
3154Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003155 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003156
Chris Lattner50b2ca42008-02-19 06:12:18 +00003157 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3158 if (I.getType()->isFPOrFPVector())
3159 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003160 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003161 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003162 if (isa<UndefValue>(Op1))
3163 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003164
3165 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003166 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3167 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003168
Reid Spencer0a783f72006-11-02 01:53:59 +00003169 return 0;
3170}
3171
3172/// This function implements the transforms common to both integer remainder
3173/// instructions (urem and srem). It is called by the visitors to those integer
3174/// remainder instructions.
3175/// @brief Common integer remainder transforms
3176Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3177 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3178
3179 if (Instruction *common = commonRemTransforms(I))
3180 return common;
3181
Dale Johannesened6af242009-01-21 00:35:19 +00003182 // 0 % X == 0 for integer, we don't need to preserve faults!
3183 if (Constant *LHS = dyn_cast<Constant>(Op0))
3184 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003185 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003186
Chris Lattner857e8cd2004-12-12 21:48:58 +00003187 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003188 // X % 0 == undef, we don't need to preserve faults!
3189 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003190 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003191
Chris Lattnera2881962003-02-18 19:28:33 +00003192 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003193 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003194
Chris Lattner97943922006-02-28 05:49:21 +00003195 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3196 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3197 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3198 return R;
3199 } else if (isa<PHINode>(Op0I)) {
3200 if (Instruction *NV = FoldOpIntoPhi(I))
3201 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003202 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003203
3204 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003205 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003206 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003207 }
Chris Lattnera2881962003-02-18 19:28:33 +00003208 }
3209
Reid Spencer0a783f72006-11-02 01:53:59 +00003210 return 0;
3211}
3212
3213Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3214 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3215
3216 if (Instruction *common = commonIRemTransforms(I))
3217 return common;
3218
3219 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3220 // X urem C^2 -> X and C
3221 // Check to see if this is an unsigned remainder with an exact power of 2,
3222 // if so, convert to a bitwise and.
3223 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003224 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003225 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003226 }
3227
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003228 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003229 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3230 if (RHSI->getOpcode() == Instruction::Shl &&
3231 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003232 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003233 Constant *N1 = Constant::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003234 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003235 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003236 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003237 }
3238 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003239 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003240
Reid Spencer0a783f72006-11-02 01:53:59 +00003241 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3242 // where C1&C2 are powers of two.
3243 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3244 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3245 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3246 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003247 if ((STO->getValue().isPowerOf2()) &&
3248 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003249 Value *TrueAnd = InsertNewInstBefore(
Dan Gohman186a6362009-08-12 16:04:34 +00003250 BinaryOperator::CreateAnd(Op0, SubOne(STO),
Owen Andersond672ecb2009-07-03 00:17:18 +00003251 SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003252 Value *FalseAnd = InsertNewInstBefore(
Dan Gohman186a6362009-08-12 16:04:34 +00003253 BinaryOperator::CreateAnd(Op0, SubOne(SFO),
Owen Andersond672ecb2009-07-03 00:17:18 +00003254 SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003255 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003256 }
3257 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003258 }
3259
Chris Lattner3f5b8772002-05-06 16:14:14 +00003260 return 0;
3261}
3262
Reid Spencer0a783f72006-11-02 01:53:59 +00003263Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3264 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3265
Dan Gohmancff55092007-11-05 23:16:33 +00003266 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003267 if (Instruction *common = commonIRemTransforms(I))
3268 return common;
3269
Dan Gohman186a6362009-08-12 16:04:34 +00003270 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003271 if (!isa<Constant>(RHSNeg) ||
3272 (isa<ConstantInt>(RHSNeg) &&
3273 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003274 // X % -Y -> X % Y
3275 AddUsesToWorkList(I);
3276 I.setOperand(1, RHSNeg);
3277 return &I;
3278 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003279
Dan Gohmancff55092007-11-05 23:16:33 +00003280 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003281 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003282 if (I.getType()->isInteger()) {
3283 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3284 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3285 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003286 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003287 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003288 }
3289
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003290 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003291 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3292 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003293
Nick Lewycky9dce8732008-12-20 16:48:00 +00003294 bool hasNegative = false;
3295 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3296 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3297 if (RHS->getValue().isNegative())
3298 hasNegative = true;
3299
3300 if (hasNegative) {
3301 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003302 for (unsigned i = 0; i != VWidth; ++i) {
3303 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3304 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003305 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003306 else
3307 Elts[i] = RHS;
3308 }
3309 }
3310
Owen Andersonaf7ec972009-07-28 21:19:26 +00003311 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003312 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003313 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003314 I.setOperand(1, NewRHSV);
3315 return &I;
3316 }
3317 }
3318 }
3319
Reid Spencer0a783f72006-11-02 01:53:59 +00003320 return 0;
3321}
3322
3323Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003324 return commonRemTransforms(I);
3325}
3326
Chris Lattner457dd822004-06-09 07:59:58 +00003327// isOneBitSet - Return true if there is exactly one bit set in the specified
3328// constant.
3329static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003330 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003331}
3332
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003333// isHighOnes - Return true if the constant is of the form 1+0+.
3334// This is the same as lowones(~X).
3335static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003336 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003337}
3338
Reid Spencere4d87aa2006-12-23 06:05:41 +00003339/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003340/// are carefully arranged to allow folding of expressions such as:
3341///
3342/// (A < B) | (A > B) --> (A != B)
3343///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003344/// Note that this is only valid if the first and second predicates have the
3345/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003346///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003347/// Three bits are used to represent the condition, as follows:
3348/// 0 A > B
3349/// 1 A == B
3350/// 2 A < B
3351///
3352/// <=> Value Definition
3353/// 000 0 Always false
3354/// 001 1 A > B
3355/// 010 2 A == B
3356/// 011 3 A >= B
3357/// 100 4 A < B
3358/// 101 5 A != B
3359/// 110 6 A <= B
3360/// 111 7 Always true
3361///
3362static unsigned getICmpCode(const ICmpInst *ICI) {
3363 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003364 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003365 case ICmpInst::ICMP_UGT: return 1; // 001
3366 case ICmpInst::ICMP_SGT: return 1; // 001
3367 case ICmpInst::ICMP_EQ: return 2; // 010
3368 case ICmpInst::ICMP_UGE: return 3; // 011
3369 case ICmpInst::ICMP_SGE: return 3; // 011
3370 case ICmpInst::ICMP_ULT: return 4; // 100
3371 case ICmpInst::ICMP_SLT: return 4; // 100
3372 case ICmpInst::ICMP_NE: return 5; // 101
3373 case ICmpInst::ICMP_ULE: return 6; // 110
3374 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003375 // True -> 7
3376 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003377 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003378 return 0;
3379 }
3380}
3381
Evan Cheng8db90722008-10-14 17:15:11 +00003382/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3383/// predicate into a three bit mask. It also returns whether it is an ordered
3384/// predicate by reference.
3385static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3386 isOrdered = false;
3387 switch (CC) {
3388 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3389 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003390 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3391 case FCmpInst::FCMP_UGT: return 1; // 001
3392 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3393 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003394 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3395 case FCmpInst::FCMP_UGE: return 3; // 011
3396 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3397 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003398 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3399 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003400 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3401 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003402 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003403 default:
3404 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003405 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003406 return 0;
3407 }
3408}
3409
Reid Spencere4d87aa2006-12-23 06:05:41 +00003410/// getICmpValue - This is the complement of getICmpCode, which turns an
3411/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003412/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003413/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003414static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003415 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003416 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003417 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003418 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003419 case 1:
3420 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003421 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003422 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003423 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3424 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003425 case 3:
3426 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003427 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003428 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003429 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003430 case 4:
3431 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003432 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003433 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003434 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3435 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003436 case 6:
3437 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003438 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003439 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003440 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003441 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003442 }
3443}
3444
Evan Cheng8db90722008-10-14 17:15:11 +00003445/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3446/// opcode and two operands into either a FCmp instruction. isordered is passed
3447/// in to determine which kind of predicate to use in the new fcmp instruction.
3448static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003449 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003450 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003451 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003452 case 0:
3453 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003454 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003455 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003456 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003457 case 1:
3458 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003459 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003460 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003461 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003462 case 2:
3463 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003464 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003465 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003466 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003467 case 3:
3468 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003469 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003470 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003471 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003472 case 4:
3473 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003474 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003475 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003476 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003477 case 5:
3478 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003479 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003480 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003481 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003482 case 6:
3483 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003484 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003485 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003486 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003487 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003488 }
3489}
3490
Chris Lattnerb9553d62008-11-16 04:55:20 +00003491/// PredicatesFoldable - Return true if both predicates match sign or if at
3492/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003493static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3494 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003495 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3496 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003497}
3498
3499namespace {
3500// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3501struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003502 InstCombiner &IC;
3503 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003504 ICmpInst::Predicate pred;
3505 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3506 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3507 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003508 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003509 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3510 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003511 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3512 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003513 return false;
3514 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003515 Instruction *apply(Instruction &Log) const {
3516 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3517 if (ICI->getOperand(0) != LHS) {
3518 assert(ICI->getOperand(1) == LHS);
3519 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003520 }
3521
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003522 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003523 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003524 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003525 unsigned Code;
3526 switch (Log.getOpcode()) {
3527 case Instruction::And: Code = LHSCode & RHSCode; break;
3528 case Instruction::Or: Code = LHSCode | RHSCode; break;
3529 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003530 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003531 }
3532
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003533 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3534 ICmpInst::isSignedPredicate(ICI->getPredicate());
3535
Owen Andersond672ecb2009-07-03 00:17:18 +00003536 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003537 if (Instruction *I = dyn_cast<Instruction>(RV))
3538 return I;
3539 // Otherwise, it's a constant boolean value...
3540 return IC.ReplaceInstUsesWith(Log, RV);
3541 }
3542};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003543} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003544
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003545// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3546// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003547// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003548Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003549 ConstantInt *OpRHS,
3550 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003551 BinaryOperator &TheAnd) {
3552 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003553 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003554 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003555 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003556
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003557 switch (Op->getOpcode()) {
3558 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003559 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003560 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003561 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003562 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003563 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003564 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003565 }
3566 break;
3567 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003568 if (Together == AndRHS) // (X | C) & C --> C
3569 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003570
Chris Lattner6e7ba452005-01-01 16:22:27 +00003571 if (Op->hasOneUse() && Together != OpRHS) {
3572 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003573 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003574 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003575 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003576 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003577 }
3578 break;
3579 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003580 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003581 // Adding a one to a single bit bit-field should be turned into an XOR
3582 // of the bit. First thing to check is to see if this AND is with a
3583 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003584 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003585
3586 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003587 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003588 // Ok, at this point, we know that we are masking the result of the
3589 // ADD down to exactly one bit. If the constant we are adding has
3590 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003591 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003592
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003593 // Check to see if any bits below the one bit set in AndRHSV are set.
3594 if ((AddRHS & (AndRHSV-1)) == 0) {
3595 // If not, the only thing that can effect the output of the AND is
3596 // the bit specified by AndRHSV. If that bit is set, the effect of
3597 // the XOR is to toggle the bit. If it is clear, then the ADD has
3598 // no effect.
3599 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3600 TheAnd.setOperand(0, X);
3601 return &TheAnd;
3602 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003603 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003604 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003605 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003606 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003607 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003608 }
3609 }
3610 }
3611 }
3612 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003613
3614 case Instruction::Shl: {
3615 // We know that the AND will not produce any of the bits shifted in, so if
3616 // the anded constant includes them, clear them now!
3617 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003618 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003619 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003620 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003621 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003622
Zhou Sheng290bec52007-03-29 08:15:12 +00003623 if (CI->getValue() == ShlMask) {
3624 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003625 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3626 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003627 TheAnd.setOperand(1, CI);
3628 return &TheAnd;
3629 }
3630 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003631 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003632 case Instruction::LShr:
3633 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003634 // We know that the AND will not produce any of the bits shifted in, so if
3635 // the anded constant includes them, clear them now! This only applies to
3636 // unsigned shifts, because a signed shr may bring in set bits!
3637 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003638 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003639 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003640 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003641 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003642
Zhou Sheng290bec52007-03-29 08:15:12 +00003643 if (CI->getValue() == ShrMask) {
3644 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003645 return ReplaceInstUsesWith(TheAnd, Op);
3646 } else if (CI != AndRHS) {
3647 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3648 return &TheAnd;
3649 }
3650 break;
3651 }
3652 case Instruction::AShr:
3653 // Signed shr.
3654 // See if this is shifting in some sign extension, then masking it out
3655 // with an and.
3656 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003657 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003658 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003659 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003660 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003661 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003662 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003663 // Make the argument unsigned.
3664 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003665 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003666 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003667 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003668 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003669 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003670 }
3671 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003672 }
3673 return 0;
3674}
3675
Chris Lattner8b170942002-08-09 23:47:40 +00003676
Chris Lattnera96879a2004-09-29 17:40:11 +00003677/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3678/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003679/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3680/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003681/// insert new instructions.
3682Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003683 bool isSigned, bool Inside,
3684 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003685 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003686 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003687 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003688
Chris Lattnera96879a2004-09-29 17:40:11 +00003689 if (Inside) {
3690 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003691 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003692
Reid Spencere4d87aa2006-12-23 06:05:41 +00003693 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003694 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003695 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003696 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003697 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003698 }
3699
3700 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003701 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003702 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003703 InsertNewInstBefore(Add, IB);
Owen Andersonbaf3c402009-07-29 18:55:55 +00003704 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003705 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003706 }
3707
3708 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003709 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003710
Reid Spencere4e40032007-03-21 23:19:50 +00003711 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003712 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003713 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003714 ICmpInst::Predicate pred = (isSigned ?
3715 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003716 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003717 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003718
Reid Spencere4e40032007-03-21 23:19:50 +00003719 // Emit V-Lo >u Hi-1-Lo
3720 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003721 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003722 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003723 InsertNewInstBefore(Add, IB);
Owen Andersonbaf3c402009-07-29 18:55:55 +00003724 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003725 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003726}
3727
Chris Lattner7203e152005-09-18 07:22:02 +00003728// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3729// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3730// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3731// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003732static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003733 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003734 uint32_t BitWidth = Val->getType()->getBitWidth();
3735 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003736
3737 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003738 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003739 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003740 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003741 return true;
3742}
3743
Chris Lattner7203e152005-09-18 07:22:02 +00003744/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3745/// where isSub determines whether the operator is a sub. If we can fold one of
3746/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003747///
3748/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3749/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3750/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3751///
3752/// return (A +/- B).
3753///
3754Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003755 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003756 Instruction &I) {
3757 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3758 if (!LHSI || LHSI->getNumOperands() != 2 ||
3759 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3760
3761 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3762
3763 switch (LHSI->getOpcode()) {
3764 default: return 0;
3765 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003766 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003767 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003768 if ((Mask->getValue().countLeadingZeros() +
3769 Mask->getValue().countPopulation()) ==
3770 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003771 break;
3772
3773 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3774 // part, we don't need any explicit masks to take them out of A. If that
3775 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003776 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003777 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003778 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003779 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003780 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003781 break;
3782 }
3783 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003784 return 0;
3785 case Instruction::Or:
3786 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003787 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003788 if ((Mask->getValue().countLeadingZeros() +
3789 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003790 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003791 break;
3792 return 0;
3793 }
3794
3795 Instruction *New;
3796 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003797 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003798 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003799 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003800 return InsertNewInstBefore(New, I);
3801}
3802
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003803/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3804Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3805 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003806 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003807 ConstantInt *LHSCst, *RHSCst;
3808 ICmpInst::Predicate LHSCC, RHSCC;
3809
Chris Lattnerea065fb2008-11-16 05:10:52 +00003810 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003811 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003812 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003813 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003814 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003815 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003816
3817 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3818 // where C is a power of 2
3819 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3820 LHSCst->getValue().isPowerOf2()) {
3821 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3822 InsertNewInstBefore(NewOr, I);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003823 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003824 }
3825
3826 // From here on, we only handle:
3827 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3828 if (Val != Val2) return 0;
3829
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003830 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3831 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3832 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3833 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3834 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3835 return 0;
3836
3837 // We can't fold (ugt x, C) & (sgt x, C2).
3838 if (!PredicatesFoldable(LHSCC, RHSCC))
3839 return 0;
3840
3841 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003842 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003843 if (ICmpInst::isSignedPredicate(LHSCC) ||
3844 (ICmpInst::isEquality(LHSCC) &&
3845 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003846 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003847 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003848 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3849
3850 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003851 std::swap(LHS, RHS);
3852 std::swap(LHSCst, RHSCst);
3853 std::swap(LHSCC, RHSCC);
3854 }
3855
3856 // At this point, we know we have have two icmp instructions
3857 // comparing a value against two constants and and'ing the result
3858 // together. Because of the above check, we know that we only have
3859 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3860 // (from the FoldICmpLogical check above), that the two constants
3861 // are not equal and that the larger constant is on the RHS
3862 assert(LHSCst != RHSCst && "Compares not folded above?");
3863
3864 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003865 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003866 case ICmpInst::ICMP_EQ:
3867 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003868 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003869 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3870 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3871 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003872 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003873 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3874 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3875 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3876 return ReplaceInstUsesWith(I, LHS);
3877 }
3878 case ICmpInst::ICMP_NE:
3879 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003880 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003881 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003882 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003883 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003884 break; // (X != 13 & X u< 15) -> no change
3885 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003886 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003887 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003888 break; // (X != 13 & X s< 15) -> no change
3889 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3890 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3891 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3892 return ReplaceInstUsesWith(I, RHS);
3893 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003894 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003895 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003896 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3897 Val->getName()+".off");
3898 InsertNewInstBefore(Add, I);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003899 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003900 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003901 }
3902 break; // (X != 13 & X != 15) -> no change
3903 }
3904 break;
3905 case ICmpInst::ICMP_ULT:
3906 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003907 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003908 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3909 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003910 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003911 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3912 break;
3913 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3914 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3915 return ReplaceInstUsesWith(I, LHS);
3916 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3917 break;
3918 }
3919 break;
3920 case ICmpInst::ICMP_SLT:
3921 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003922 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003923 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3924 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003925 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003926 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3927 break;
3928 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3929 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3930 return ReplaceInstUsesWith(I, LHS);
3931 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3932 break;
3933 }
3934 break;
3935 case ICmpInst::ICMP_UGT:
3936 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003937 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003938 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3939 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3940 return ReplaceInstUsesWith(I, RHS);
3941 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3942 break;
3943 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003944 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003945 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003946 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003947 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003948 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003949 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003950 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3951 break;
3952 }
3953 break;
3954 case ICmpInst::ICMP_SGT:
3955 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003956 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003957 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3958 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3959 return ReplaceInstUsesWith(I, RHS);
3960 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3961 break;
3962 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003963 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003964 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003965 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003966 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003967 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003968 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003969 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3970 break;
3971 }
3972 break;
3973 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003974
3975 return 0;
3976}
3977
Chris Lattner42d1be02009-07-23 05:14:02 +00003978Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3979 FCmpInst *RHS) {
3980
3981 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3982 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3983 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3984 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3985 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3986 // If either of the constants are nans, then the whole thing returns
3987 // false.
3988 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00003989 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003990 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00003991 LHS->getOperand(0), RHS->getOperand(0));
3992 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003993
3994 // Handle vector zeros. This occurs because the canonical form of
3995 // "fcmp ord x,x" is "fcmp ord x, 0".
3996 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3997 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003998 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00003999 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00004000 return 0;
4001 }
4002
4003 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4004 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4005 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4006
4007
4008 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4009 // Swap RHS operands to match LHS.
4010 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4011 std::swap(Op1LHS, Op1RHS);
4012 }
4013
4014 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4015 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4016 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004017 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004018
4019 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004020 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004021 if (Op0CC == FCmpInst::FCMP_TRUE)
4022 return ReplaceInstUsesWith(I, RHS);
4023 if (Op1CC == FCmpInst::FCMP_TRUE)
4024 return ReplaceInstUsesWith(I, LHS);
4025
4026 bool Op0Ordered;
4027 bool Op1Ordered;
4028 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4029 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4030 if (Op1Pred == 0) {
4031 std::swap(LHS, RHS);
4032 std::swap(Op0Pred, Op1Pred);
4033 std::swap(Op0Ordered, Op1Ordered);
4034 }
4035 if (Op0Pred == 0) {
4036 // uno && ueq -> uno && (uno || eq) -> ueq
4037 // ord && olt -> ord && (ord && lt) -> olt
4038 if (Op0Ordered == Op1Ordered)
4039 return ReplaceInstUsesWith(I, RHS);
4040
4041 // uno && oeq -> uno && (ord && eq) -> false
4042 // uno && ord -> false
4043 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004044 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004045 // ord && ueq -> ord && (uno || eq) -> oeq
4046 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4047 Op0LHS, Op0RHS, Context));
4048 }
4049 }
4050
4051 return 0;
4052}
4053
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004054
Chris Lattner7e708292002-06-25 16:13:24 +00004055Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004056 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004057 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004058
Chris Lattnere87597f2004-10-16 18:11:37 +00004059 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004060 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004061
Chris Lattner6e7ba452005-01-01 16:22:27 +00004062 // and X, X = X
4063 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004064 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004065
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004066 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004067 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004068 if (SimplifyDemandedInstructionBits(I))
4069 return &I;
4070 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004071 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004072 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004073 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004074 } else if (isa<ConstantAggregateZero>(Op1)) {
4075 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004076 }
4077 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004078
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004079 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004080 const APInt& AndRHSMask = AndRHS->getValue();
4081 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004082
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004083 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004084 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004085 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004086 Value *Op0LHS = Op0I->getOperand(0);
4087 Value *Op0RHS = Op0I->getOperand(1);
4088 switch (Op0I->getOpcode()) {
4089 case Instruction::Xor:
4090 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004091 // If the mask is only needed on one incoming arm, push it up.
4092 if (Op0I->hasOneUse()) {
4093 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4094 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004095 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004096 Op0RHS->getName()+".masked");
4097 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004098 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004099 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004100 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004101 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004102 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4103 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004104 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004105 Op0LHS->getName()+".masked");
4106 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004107 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004108 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4109 }
4110 }
4111
Chris Lattner6e7ba452005-01-01 16:22:27 +00004112 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004113 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004114 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4115 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4116 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4117 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004118 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004119 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004120 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004121 break;
4122
4123 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004124 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4125 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4126 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4127 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004128 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004129
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004130 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4131 // has 1's for all bits that the subtraction with A might affect.
4132 if (Op0I->hasOneUse()) {
4133 uint32_t BitWidth = AndRHSMask.getBitWidth();
4134 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4135 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4136
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004137 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004138 if (!(A && A->isZero()) && // avoid infinite recursion.
4139 MaskedValueIsZero(Op0LHS, Mask)) {
Dan Gohman4ae51262009-08-12 16:23:25 +00004140 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004141 InsertNewInstBefore(NewNeg, I);
4142 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4143 }
4144 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004145 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004146
4147 case Instruction::Shl:
4148 case Instruction::LShr:
4149 // (1 << x) & 1 --> zext(x == 0)
4150 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004151 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004152 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00004153 Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004154 InsertNewInstBefore(NewICmp, I);
4155 return new ZExtInst(NewICmp, I.getType());
4156 }
4157 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004158 }
4159
Chris Lattner58403262003-07-23 19:25:52 +00004160 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004161 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004162 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004163 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004164 // If this is an integer truncation or change from signed-to-unsigned, and
4165 // if the source is an and/or with immediate, transform it. This
4166 // frequently occurs for bitfield accesses.
4167 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004168 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004169 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004170 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004171 if (CastOp->getOpcode() == Instruction::And) {
4172 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004173 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4174 // This will fold the two constants together, which may allow
4175 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004176 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004177 CastOp->getOperand(0), I.getType(),
4178 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004179 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004180 // trunc_or_bitcast(C1)&C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004181 Constant *C3 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004182 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4183 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004184 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004185 } else if (CastOp->getOpcode() == Instruction::Or) {
4186 // Change: and (cast (or X, C1) to T), C2
4187 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004188 Constant *C3 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004189 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4190 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004191 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004192 return ReplaceInstUsesWith(I, AndRHS);
4193 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004194 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004195 }
Chris Lattner06782f82003-07-23 19:36:21 +00004196 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004197
4198 // Try to fold constant and into select arguments.
4199 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004200 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004201 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004202 if (isa<PHINode>(Op0))
4203 if (Instruction *NV = FoldOpIntoPhi(I))
4204 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004205 }
4206
Dan Gohman186a6362009-08-12 16:04:34 +00004207 Value *Op0NotVal = dyn_castNotVal(Op0);
4208 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004209
Chris Lattner5b62aa72004-06-18 06:07:51 +00004210 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004211 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004212
Misha Brukmancb6267b2004-07-30 12:50:08 +00004213 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004214 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004215 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004216 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004217 InsertNewInstBefore(Or, I);
Dan Gohman4ae51262009-08-12 16:23:25 +00004218 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004219 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004220
4221 {
Chris Lattner003b6202007-06-15 05:58:24 +00004222 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004223 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004224 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4225 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004226
4227 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004228 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004229 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004230 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004231 }
4232 }
4233
Dan Gohman4ae51262009-08-12 16:23:25 +00004234 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004235 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4236 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004237
4238 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004239 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004240 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004241 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004242 }
4243 }
Chris Lattner64daab52006-04-01 08:03:55 +00004244
4245 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004246 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004247 if (A == Op1) { // (A^B)&A -> A&(A^B)
4248 I.swapOperands(); // Simplify below
4249 std::swap(Op0, Op1);
4250 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4251 cast<BinaryOperator>(Op0)->swapOperands();
4252 I.swapOperands(); // Simplify below
4253 std::swap(Op0, Op1);
4254 }
4255 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004256
Chris Lattner64daab52006-04-01 08:03:55 +00004257 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004258 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004259 if (B == Op0) { // B&(A^B) -> B&(B^A)
4260 cast<BinaryOperator>(Op1)->swapOperands();
4261 std::swap(A, B);
4262 }
4263 if (A == Op0) { // A&(A^B) -> A & ~B
Dan Gohman4ae51262009-08-12 16:23:25 +00004264 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004265 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004266 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004267 }
4268 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004269
4270 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004271 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4272 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004273 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004274 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4275 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004276 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004277 }
4278
Reid Spencere4d87aa2006-12-23 06:05:41 +00004279 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4280 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004281 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004282 return R;
4283
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004284 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4285 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4286 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004287 }
4288
Chris Lattner6fc205f2006-05-05 06:39:07 +00004289 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004290 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4291 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4292 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4293 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004294 if (SrcTy == Op1C->getOperand(0)->getType() &&
4295 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004296 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004297 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4298 I.getType(), TD) &&
4299 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4300 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004301 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004302 Op1C->getOperand(0),
4303 I.getName());
4304 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004305 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004306 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004307 }
Chris Lattnere511b742006-11-14 07:46:50 +00004308
4309 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004310 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4311 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4312 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004313 SI0->getOperand(1) == SI1->getOperand(1) &&
4314 (SI0->hasOneUse() || SI1->hasOneUse())) {
4315 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004316 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004317 SI1->getOperand(0),
4318 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004319 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004320 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004321 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004322 }
4323
Evan Cheng8db90722008-10-14 17:15:11 +00004324 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004325 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004326 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4327 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4328 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004329 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004330
Chris Lattner7e708292002-06-25 16:13:24 +00004331 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004332}
4333
Chris Lattner8c34cd22008-10-05 02:13:19 +00004334/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4335/// capable of providing pieces of a bswap. The subexpression provides pieces
4336/// of a bswap if it is proven that each of the non-zero bytes in the output of
4337/// the expression came from the corresponding "byte swapped" byte in some other
4338/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4339/// we know that the expression deposits the low byte of %X into the high byte
4340/// of the bswap result and that all other bytes are zero. This expression is
4341/// accepted, the high byte of ByteValues is set to X to indicate a correct
4342/// match.
4343///
4344/// This function returns true if the match was unsuccessful and false if so.
4345/// On entry to the function the "OverallLeftShift" is a signed integer value
4346/// indicating the number of bytes that the subexpression is later shifted. For
4347/// example, if the expression is later right shifted by 16 bits, the
4348/// OverallLeftShift value would be -2 on entry. This is used to specify which
4349/// byte of ByteValues is actually being set.
4350///
4351/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4352/// byte is masked to zero by a user. For example, in (X & 255), X will be
4353/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4354/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4355/// always in the local (OverallLeftShift) coordinate space.
4356///
4357static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4358 SmallVector<Value*, 8> &ByteValues) {
4359 if (Instruction *I = dyn_cast<Instruction>(V)) {
4360 // If this is an or instruction, it may be an inner node of the bswap.
4361 if (I->getOpcode() == Instruction::Or) {
4362 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4363 ByteValues) ||
4364 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4365 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004366 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004367
4368 // If this is a logical shift by a constant multiple of 8, recurse with
4369 // OverallLeftShift and ByteMask adjusted.
4370 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4371 unsigned ShAmt =
4372 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4373 // Ensure the shift amount is defined and of a byte value.
4374 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4375 return true;
4376
4377 unsigned ByteShift = ShAmt >> 3;
4378 if (I->getOpcode() == Instruction::Shl) {
4379 // X << 2 -> collect(X, +2)
4380 OverallLeftShift += ByteShift;
4381 ByteMask >>= ByteShift;
4382 } else {
4383 // X >>u 2 -> collect(X, -2)
4384 OverallLeftShift -= ByteShift;
4385 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004386 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004387 }
4388
4389 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4390 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4391
4392 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4393 ByteValues);
4394 }
4395
4396 // If this is a logical 'and' with a mask that clears bytes, clear the
4397 // corresponding bytes in ByteMask.
4398 if (I->getOpcode() == Instruction::And &&
4399 isa<ConstantInt>(I->getOperand(1))) {
4400 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4401 unsigned NumBytes = ByteValues.size();
4402 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4403 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4404
4405 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4406 // If this byte is masked out by a later operation, we don't care what
4407 // the and mask is.
4408 if ((ByteMask & (1 << i)) == 0)
4409 continue;
4410
4411 // If the AndMask is all zeros for this byte, clear the bit.
4412 APInt MaskB = AndMask & Byte;
4413 if (MaskB == 0) {
4414 ByteMask &= ~(1U << i);
4415 continue;
4416 }
4417
4418 // If the AndMask is not all ones for this byte, it's not a bytezap.
4419 if (MaskB != Byte)
4420 return true;
4421
4422 // Otherwise, this byte is kept.
4423 }
4424
4425 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4426 ByteValues);
4427 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004428 }
4429
Chris Lattner8c34cd22008-10-05 02:13:19 +00004430 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4431 // the input value to the bswap. Some observations: 1) if more than one byte
4432 // is demanded from this input, then it could not be successfully assembled
4433 // into a byteswap. At least one of the two bytes would not be aligned with
4434 // their ultimate destination.
4435 if (!isPowerOf2_32(ByteMask)) return true;
4436 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004437
Chris Lattner8c34cd22008-10-05 02:13:19 +00004438 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4439 // is demanded, it needs to go into byte 0 of the result. This means that the
4440 // byte needs to be shifted until it lands in the right byte bucket. The
4441 // shift amount depends on the position: if the byte is coming from the high
4442 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4443 // low part, it must be shifted left.
4444 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4445 if (InputByteNo < ByteValues.size()/2) {
4446 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4447 return true;
4448 } else {
4449 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4450 return true;
4451 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004452
4453 // If the destination byte value is already defined, the values are or'd
4454 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004455 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004456 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004457 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004458 return false;
4459}
4460
4461/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4462/// If so, insert the new bswap intrinsic and return it.
4463Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004464 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004465 if (!ITy || ITy->getBitWidth() % 16 ||
4466 // ByteMask only allows up to 32-byte values.
4467 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004468 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004469
4470 /// ByteValues - For each byte of the result, we keep track of which value
4471 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004472 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004473 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004474
4475 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004476 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4477 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004478 return 0;
4479
4480 // Check to see if all of the bytes come from the same value.
4481 Value *V = ByteValues[0];
4482 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4483
4484 // Check to make sure that all of the bytes come from the same value.
4485 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4486 if (ByteValues[i] != V)
4487 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004488 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004489 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004490 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004491 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004492}
4493
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004494/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4495/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4496/// we can simplify this expression to "cond ? C : D or B".
4497static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004498 Value *C, Value *D,
4499 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004500 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004501 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004502 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004503 return 0;
4504
Chris Lattnera6a474d2008-11-16 04:26:55 +00004505 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004506 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004507 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004508 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004509 return SelectInst::Create(Cond, C, B);
4510 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004511 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004512 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004513 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004514 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004515 return 0;
4516}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004517
Chris Lattner69d4ced2008-11-16 05:20:07 +00004518/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4519Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4520 ICmpInst *LHS, ICmpInst *RHS) {
4521 Value *Val, *Val2;
4522 ConstantInt *LHSCst, *RHSCst;
4523 ICmpInst::Predicate LHSCC, RHSCC;
4524
4525 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004526 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004527 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004528 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004529 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004530 return 0;
4531
4532 // From here on, we only handle:
4533 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4534 if (Val != Val2) return 0;
4535
4536 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4537 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4538 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4539 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4540 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4541 return 0;
4542
4543 // We can't fold (ugt x, C) | (sgt x, C2).
4544 if (!PredicatesFoldable(LHSCC, RHSCC))
4545 return 0;
4546
4547 // Ensure that the larger constant is on the RHS.
4548 bool ShouldSwap;
4549 if (ICmpInst::isSignedPredicate(LHSCC) ||
4550 (ICmpInst::isEquality(LHSCC) &&
4551 ICmpInst::isSignedPredicate(RHSCC)))
4552 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4553 else
4554 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4555
4556 if (ShouldSwap) {
4557 std::swap(LHS, RHS);
4558 std::swap(LHSCst, RHSCst);
4559 std::swap(LHSCC, RHSCC);
4560 }
4561
4562 // At this point, we know we have have two icmp instructions
4563 // comparing a value against two constants and or'ing the result
4564 // together. Because of the above check, we know that we only have
4565 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4566 // FoldICmpLogical check above), that the two constants are not
4567 // equal.
4568 assert(LHSCst != RHSCst && "Compares not folded above?");
4569
4570 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004571 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004572 case ICmpInst::ICMP_EQ:
4573 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004574 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004575 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004576 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004577 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004578 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004579 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4580 Val->getName()+".off");
4581 InsertNewInstBefore(Add, I);
Dan Gohman186a6362009-08-12 16:04:34 +00004582 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004583 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004584 }
4585 break; // (X == 13 | X == 15) -> no change
4586 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4587 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4588 break;
4589 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4590 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4591 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4592 return ReplaceInstUsesWith(I, RHS);
4593 }
4594 break;
4595 case ICmpInst::ICMP_NE:
4596 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004597 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004598 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4599 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4600 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4601 return ReplaceInstUsesWith(I, LHS);
4602 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4603 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4604 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004605 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004606 }
4607 break;
4608 case ICmpInst::ICMP_ULT:
4609 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004610 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004611 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4612 break;
4613 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4614 // If RHSCst is [us]MAXINT, it is always false. Not handling
4615 // this can cause overflow.
4616 if (RHSCst->isMaxValue(false))
4617 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004618 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004619 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004620 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4621 break;
4622 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4623 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4624 return ReplaceInstUsesWith(I, RHS);
4625 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4626 break;
4627 }
4628 break;
4629 case ICmpInst::ICMP_SLT:
4630 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004631 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004632 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4633 break;
4634 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4635 // If RHSCst is [us]MAXINT, it is always false. Not handling
4636 // this can cause overflow.
4637 if (RHSCst->isMaxValue(true))
4638 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004639 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004640 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004641 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4642 break;
4643 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4644 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4645 return ReplaceInstUsesWith(I, RHS);
4646 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4647 break;
4648 }
4649 break;
4650 case ICmpInst::ICMP_UGT:
4651 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004652 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004653 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4654 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4655 return ReplaceInstUsesWith(I, LHS);
4656 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4657 break;
4658 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4659 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004660 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004661 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4662 break;
4663 }
4664 break;
4665 case ICmpInst::ICMP_SGT:
4666 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004667 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004668 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4669 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4670 return ReplaceInstUsesWith(I, LHS);
4671 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4672 break;
4673 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4674 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004675 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004676 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4677 break;
4678 }
4679 break;
4680 }
4681 return 0;
4682}
4683
Chris Lattner5414cc52009-07-23 05:46:22 +00004684Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4685 FCmpInst *RHS) {
4686 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4687 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4688 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4689 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4690 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4691 // If either of the constants are nans, then the whole thing returns
4692 // true.
4693 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004694 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004695
4696 // Otherwise, no need to compare the two constants, compare the
4697 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004698 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004699 LHS->getOperand(0), RHS->getOperand(0));
4700 }
4701
4702 // Handle vector zeros. This occurs because the canonical form of
4703 // "fcmp uno x,x" is "fcmp uno x, 0".
4704 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4705 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004706 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004707 LHS->getOperand(0), RHS->getOperand(0));
4708
4709 return 0;
4710 }
4711
4712 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4713 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4714 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4715
4716 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4717 // Swap RHS operands to match LHS.
4718 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4719 std::swap(Op1LHS, Op1RHS);
4720 }
4721 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4722 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4723 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004724 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004725 Op0LHS, Op0RHS);
4726 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004727 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004728 if (Op0CC == FCmpInst::FCMP_FALSE)
4729 return ReplaceInstUsesWith(I, RHS);
4730 if (Op1CC == FCmpInst::FCMP_FALSE)
4731 return ReplaceInstUsesWith(I, LHS);
4732 bool Op0Ordered;
4733 bool Op1Ordered;
4734 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4735 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4736 if (Op0Ordered == Op1Ordered) {
4737 // If both are ordered or unordered, return a new fcmp with
4738 // or'ed predicates.
4739 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4740 Op0LHS, Op0RHS, Context);
4741 if (Instruction *I = dyn_cast<Instruction>(RV))
4742 return I;
4743 // Otherwise, it's a constant boolean value...
4744 return ReplaceInstUsesWith(I, RV);
4745 }
4746 }
4747 return 0;
4748}
4749
Bill Wendlinga698a472008-12-01 08:23:25 +00004750/// FoldOrWithConstants - This helper function folds:
4751///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004752/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004753///
4754/// into:
4755///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004756/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004757///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004758/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004759Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004760 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004761 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4762 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004763
Bill Wendling286a0542008-12-02 06:24:20 +00004764 Value *V1 = 0;
4765 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004766 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004767
Bill Wendling29976b92008-12-02 06:18:11 +00004768 APInt Xor = CI1->getValue() ^ CI2->getValue();
4769 if (!Xor.isAllOnesValue()) return 0;
4770
Bill Wendling286a0542008-12-02 06:24:20 +00004771 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004772 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004773 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4774 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004775 }
4776
4777 return 0;
4778}
4779
Chris Lattner7e708292002-06-25 16:13:24 +00004780Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004781 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004782 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004783
Chris Lattner42593e62007-03-24 23:56:43 +00004784 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004785 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004786
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004787 // or X, X = X
4788 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004789 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004790
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004791 // See if we can simplify any instructions used by the instruction whose sole
4792 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004793 if (SimplifyDemandedInstructionBits(I))
4794 return &I;
4795 if (isa<VectorType>(I.getType())) {
4796 if (isa<ConstantAggregateZero>(Op1)) {
4797 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4798 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4799 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4800 return ReplaceInstUsesWith(I, I.getOperand(1));
4801 }
Chris Lattner42593e62007-03-24 23:56:43 +00004802 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004803
Chris Lattner3f5b8772002-05-06 16:14:14 +00004804 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004805 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004806 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004807 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004808 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004809 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004810 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004811 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004812 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004813 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004814 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004815 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004816
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004817 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004818 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004819 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004820 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004821 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004822 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004823 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004824 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004825 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004826
4827 // Try to fold constant and into select arguments.
4828 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004829 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004830 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004831 if (isa<PHINode>(Op0))
4832 if (Instruction *NV = FoldOpIntoPhi(I))
4833 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004834 }
4835
Chris Lattner4f637d42006-01-06 17:59:59 +00004836 Value *A = 0, *B = 0;
4837 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004838
Dan Gohman4ae51262009-08-12 16:23:25 +00004839 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004840 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4841 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004842 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004843 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4844 return ReplaceInstUsesWith(I, Op0);
4845
Chris Lattner6423d4c2006-07-10 20:25:24 +00004846 // (A | B) | C and A | (B | C) -> bswap if possible.
4847 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004848 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4849 match(Op1, m_Or(m_Value(), m_Value())) ||
4850 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4851 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004852 if (Instruction *BSwap = MatchBSwap(I))
4853 return BSwap;
4854 }
4855
Chris Lattner6e4c6492005-05-09 04:58:36 +00004856 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004857 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004858 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004859 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004860 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004861 InsertNewInstBefore(NOr, I);
4862 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004863 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004864 }
4865
4866 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004867 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004868 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004869 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004870 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004871 InsertNewInstBefore(NOr, I);
4872 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004873 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004874 }
4875
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004876 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004877 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004878 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4879 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004880 Value *V1 = 0, *V2 = 0, *V3 = 0;
4881 C1 = dyn_cast<ConstantInt>(C);
4882 C2 = dyn_cast<ConstantInt>(D);
4883 if (C1 && C2) { // (A & C1)|(B & C2)
4884 // If we have: ((V + N) & C1) | (V & C2)
4885 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4886 // replace with V+N.
4887 if (C1->getValue() == ~C2->getValue()) {
4888 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004889 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004890 // Add commutes, try both ways.
4891 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4892 return ReplaceInstUsesWith(I, A);
4893 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4894 return ReplaceInstUsesWith(I, A);
4895 }
4896 // Or commutes, try both ways.
4897 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004898 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004899 // Add commutes, try both ways.
4900 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4901 return ReplaceInstUsesWith(I, B);
4902 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4903 return ReplaceInstUsesWith(I, B);
4904 }
4905 }
Chris Lattner044e5332007-04-08 08:01:49 +00004906 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004907 }
4908
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004909 // Check to see if we have any common things being and'ed. If so, find the
4910 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004911 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4912 if (A == B) // (A & C)|(A & D) == A & (C|D)
4913 V1 = A, V2 = C, V3 = D;
4914 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4915 V1 = A, V2 = B, V3 = C;
4916 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4917 V1 = C, V2 = A, V3 = D;
4918 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4919 V1 = C, V2 = A, V3 = B;
4920
4921 if (V1) {
4922 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004923 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4924 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004925 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004926 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004927
Dan Gohman1975d032008-10-30 20:40:10 +00004928 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004929 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004930 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004931 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004932 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004933 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004934 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004935 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004936 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004937
Bill Wendlingb01865c2008-11-30 13:52:49 +00004938 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004939 if ((match(C, m_Not(m_Specific(D))) &&
4940 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004941 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004942 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004943 if ((match(A, m_Not(m_Specific(D))) &&
4944 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004945 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004946 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004947 if ((match(C, m_Not(m_Specific(B))) &&
4948 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004949 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004950 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004951 if ((match(A, m_Not(m_Specific(B))) &&
4952 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004953 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004954 }
Chris Lattnere511b742006-11-14 07:46:50 +00004955
4956 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004957 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4958 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4959 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004960 SI0->getOperand(1) == SI1->getOperand(1) &&
4961 (SI0->hasOneUse() || SI1->hasOneUse())) {
4962 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004963 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004964 SI1->getOperand(0),
4965 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004966 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004967 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004968 }
4969 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004970
Bill Wendlingb3833d12008-12-01 01:07:11 +00004971 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004972 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4973 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004974 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004975 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004976 }
4977 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004978 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4979 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004980 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004981 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004982 }
4983
Dan Gohman4ae51262009-08-12 16:23:25 +00004984 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004985 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004986 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004987 } else {
4988 A = 0;
4989 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004990 // Note, A is still live here!
Dan Gohman4ae51262009-08-12 16:23:25 +00004991 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004992 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004993 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004994
Misha Brukmancb6267b2004-07-30 12:50:08 +00004995 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004996 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004997 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004998 I.getName()+".demorgan"), I);
Dan Gohman4ae51262009-08-12 16:23:25 +00004999 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005000 }
Chris Lattnera27231a2003-03-10 23:13:59 +00005001 }
Chris Lattnera2881962003-02-18 19:28:33 +00005002
Reid Spencere4d87aa2006-12-23 06:05:41 +00005003 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5004 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00005005 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005006 return R;
5007
Chris Lattner69d4ced2008-11-16 05:20:07 +00005008 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5009 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5010 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00005011 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005012
5013 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005014 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005015 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005016 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00005017 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5018 !isa<ICmpInst>(Op1C->getOperand(0))) {
5019 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00005020 if (SrcTy == Op1C->getOperand(0)->getType() &&
5021 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00005022 // Only do this if the casts both really cause code to be
5023 // generated.
5024 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5025 I.getType(), TD) &&
5026 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5027 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005028 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00005029 Op1C->getOperand(0),
5030 I.getName());
5031 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005032 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005033 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005034 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005035 }
Chris Lattner99c65742007-10-24 05:38:08 +00005036 }
5037
5038
5039 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5040 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005041 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5042 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5043 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005044 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005045
Chris Lattner7e708292002-06-25 16:13:24 +00005046 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005047}
5048
Dan Gohman844731a2008-05-13 00:00:25 +00005049namespace {
5050
Chris Lattnerc317d392004-02-16 01:20:27 +00005051// XorSelf - Implements: X ^ X --> 0
5052struct XorSelf {
5053 Value *RHS;
5054 XorSelf(Value *rhs) : RHS(rhs) {}
5055 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5056 Instruction *apply(BinaryOperator &Xor) const {
5057 return &Xor;
5058 }
5059};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005060
Dan Gohman844731a2008-05-13 00:00:25 +00005061}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005062
Chris Lattner7e708292002-06-25 16:13:24 +00005063Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005064 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005065 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005066
Evan Chengd34af782008-03-25 20:07:13 +00005067 if (isa<UndefValue>(Op1)) {
5068 if (isa<UndefValue>(Op0))
5069 // Handle undef ^ undef -> 0 special case. This is a common
5070 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005071 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005072 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005073 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005074
Chris Lattnerc317d392004-02-16 01:20:27 +00005075 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005076 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005077 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005078 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005079 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005080
5081 // See if we can simplify any instructions used by the instruction whose sole
5082 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005083 if (SimplifyDemandedInstructionBits(I))
5084 return &I;
5085 if (isa<VectorType>(I.getType()))
5086 if (isa<ConstantAggregateZero>(Op1))
5087 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005088
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005089 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005090 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005091 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5092 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5093 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5094 if (Op0I->getOpcode() == Instruction::And ||
5095 Op0I->getOpcode() == Instruction::Or) {
Dan Gohman186a6362009-08-12 16:04:34 +00005096 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5097 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005098 Instruction *NotY =
Dan Gohman4ae51262009-08-12 16:23:25 +00005099 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005100 Op0I->getOperand(1)->getName()+".not");
5101 InsertNewInstBefore(NotY, I);
5102 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005103 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005104 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005105 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005106 }
5107 }
5108 }
5109 }
5110
5111
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005112 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson5defacc2009-07-31 17:39:07 +00005113 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005114 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005115 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005116 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005117 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005118
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005119 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005120 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005121 FCI->getOperand(0), FCI->getOperand(1));
5122 }
5123
Nick Lewycky517e1f52008-05-31 19:01:33 +00005124 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5125 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5126 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5127 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5128 Instruction::CastOps Opcode = Op0C->getOpcode();
5129 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005130 if (RHS == ConstantExpr::getCast(Opcode,
Owen Anderson5defacc2009-07-31 17:39:07 +00005131 ConstantInt::getTrue(*Context),
Nick Lewycky517e1f52008-05-31 19:01:33 +00005132 Op0C->getDestTy())) {
5133 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5134 CI->getOpcode(), CI->getInversePredicate(),
5135 CI->getOperand(0), CI->getOperand(1)), I);
5136 NewCI->takeName(CI);
5137 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5138 }
5139 }
5140 }
5141 }
5142 }
5143
Reid Spencere4d87aa2006-12-23 06:05:41 +00005144 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005145 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005146 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5147 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005148 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5149 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005150 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005151 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005152 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005153
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005154 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005155 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005156 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005157 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005158 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005159 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005160 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005161 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005162 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005163 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005164 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005165 Constant *C = ConstantInt::get(*Context,
5166 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005167 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005168
Chris Lattner7c4049c2004-01-12 19:35:11 +00005169 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005170 } else if (Op0I->getOpcode() == Instruction::Or) {
5171 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005172 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005173 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005174 // Anything in both C1 and C2 is known to be zero, remove it from
5175 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005176 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5177 NewRHS = ConstantExpr::getAnd(NewRHS,
5178 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005179 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005180 I.setOperand(0, Op0I->getOperand(0));
5181 I.setOperand(1, NewRHS);
5182 return &I;
5183 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005184 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005185 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005186 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005187
5188 // Try to fold constant and into select arguments.
5189 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005190 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005191 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005192 if (isa<PHINode>(Op0))
5193 if (Instruction *NV = FoldOpIntoPhi(I))
5194 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005195 }
5196
Dan Gohman186a6362009-08-12 16:04:34 +00005197 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005198 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005199 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005200
Dan Gohman186a6362009-08-12 16:04:34 +00005201 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005202 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005203 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005204
Chris Lattner318bf792007-03-18 22:51:34 +00005205
5206 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5207 if (Op1I) {
5208 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005209 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005210 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005211 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005212 I.swapOperands();
5213 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005214 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005215 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005216 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005217 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005218 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005219 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005220 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005221 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005222 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005223 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005224 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005225 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005226 std::swap(A, B);
5227 }
Chris Lattner318bf792007-03-18 22:51:34 +00005228 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005229 I.swapOperands(); // Simplified below.
5230 std::swap(Op0, Op1);
5231 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005232 }
Chris Lattner318bf792007-03-18 22:51:34 +00005233 }
5234
5235 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5236 if (Op0I) {
5237 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005238 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005239 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005240 if (A == Op1) // (B|A)^B == (A|B)^B
5241 std::swap(A, B);
5242 if (B == Op1) { // (A|B)^B == A & ~B
5243 Instruction *NotB =
Dan Gohman4ae51262009-08-12 16:23:25 +00005244 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005245 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005246 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005247 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005248 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005249 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005250 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005251 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005252 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005253 if (A == Op1) // (A&B)^A -> (B&A)^A
5254 std::swap(A, B);
5255 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005256 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005257 Instruction *N =
Dan Gohman4ae51262009-08-12 16:23:25 +00005258 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005259 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005260 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005261 }
Chris Lattner318bf792007-03-18 22:51:34 +00005262 }
5263
5264 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5265 if (Op0I && Op1I && Op0I->isShift() &&
5266 Op0I->getOpcode() == Op1I->getOpcode() &&
5267 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5268 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5269 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005270 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005271 Op1I->getOperand(0),
5272 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005273 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005274 Op1I->getOperand(1));
5275 }
5276
5277 if (Op0I && Op1I) {
5278 Value *A, *B, *C, *D;
5279 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005280 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5281 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005282 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005283 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005284 }
5285 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005286 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5287 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005288 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005289 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005290 }
5291
5292 // (A & B)^(C & D)
5293 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005294 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5295 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005296 // (X & Y)^(X & Y) -> (Y^Z) & X
5297 Value *X = 0, *Y = 0, *Z = 0;
5298 if (A == C)
5299 X = A, Y = B, Z = D;
5300 else if (A == D)
5301 X = A, Y = B, Z = C;
5302 else if (B == C)
5303 X = B, Y = A, Z = D;
5304 else if (B == D)
5305 X = B, Y = A, Z = C;
5306
5307 if (X) {
5308 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005309 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5310 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005311 }
5312 }
5313 }
5314
Reid Spencere4d87aa2006-12-23 06:05:41 +00005315 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5316 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005317 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005318 return R;
5319
Chris Lattner6fc205f2006-05-05 06:39:07 +00005320 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005321 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005322 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005323 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5324 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005325 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005326 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005327 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5328 I.getType(), TD) &&
5329 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5330 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005331 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005332 Op1C->getOperand(0),
5333 I.getName());
5334 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005335 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005336 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005337 }
Chris Lattner99c65742007-10-24 05:38:08 +00005338 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005339
Chris Lattner7e708292002-06-25 16:13:24 +00005340 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005341}
5342
Owen Andersond672ecb2009-07-03 00:17:18 +00005343static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005344 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005345 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005346}
Chris Lattnera96879a2004-09-29 17:40:11 +00005347
Dan Gohman6de29f82009-06-15 22:12:54 +00005348static bool HasAddOverflow(ConstantInt *Result,
5349 ConstantInt *In1, ConstantInt *In2,
5350 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005351 if (IsSigned)
5352 if (In2->getValue().isNegative())
5353 return Result->getValue().sgt(In1->getValue());
5354 else
5355 return Result->getValue().slt(In1->getValue());
5356 else
5357 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005358}
5359
Dan Gohman6de29f82009-06-15 22:12:54 +00005360/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005361/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005362static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005363 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005364 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005365 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005366
Dan Gohman6de29f82009-06-15 22:12:54 +00005367 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5368 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005369 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005370 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5371 ExtractElement(In1, Idx, Context),
5372 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005373 IsSigned))
5374 return true;
5375 }
5376 return false;
5377 }
5378
5379 return HasAddOverflow(cast<ConstantInt>(Result),
5380 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5381 IsSigned);
5382}
5383
5384static bool HasSubOverflow(ConstantInt *Result,
5385 ConstantInt *In1, ConstantInt *In2,
5386 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005387 if (IsSigned)
5388 if (In2->getValue().isNegative())
5389 return Result->getValue().slt(In1->getValue());
5390 else
5391 return Result->getValue().sgt(In1->getValue());
5392 else
5393 return Result->getValue().ugt(In1->getValue());
5394}
5395
Dan Gohman6de29f82009-06-15 22:12:54 +00005396/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5397/// overflowed for this type.
5398static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005399 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005400 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005401 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005402
5403 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5404 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005405 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005406 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5407 ExtractElement(In1, Idx, Context),
5408 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005409 IsSigned))
5410 return true;
5411 }
5412 return false;
5413 }
5414
5415 return HasSubOverflow(cast<ConstantInt>(Result),
5416 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5417 IsSigned);
5418}
5419
Chris Lattner574da9b2005-01-13 20:14:25 +00005420/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5421/// code necessary to compute the offset from the base pointer (without adding
5422/// in the base pointer). Return the result as a signed integer of intptr size.
5423static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005424 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005425 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson1d0be152009-08-13 21:58:54 +00005426 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Anderson07cf79e2009-07-06 23:00:19 +00005427 LLVMContext *Context = IC.getContext();
Owen Andersona7235ea2009-07-31 20:28:14 +00005428 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005429
5430 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005431 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005432 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005433
Gabor Greif177dd3f2008-06-12 21:37:33 +00005434 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5435 ++i, ++GTI) {
5436 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005437 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005438 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5439 if (OpC->isZero()) continue;
5440
5441 // Handle a struct index, which adds its field offset to the pointer.
5442 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5443 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5444
5445 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005446 Result =
Owen Andersoneed707b2009-07-24 23:12:02 +00005447 ConstantInt::get(*Context,
5448 RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005449 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005450 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005451 BinaryOperator::CreateAdd(Result,
Owen Andersoneed707b2009-07-24 23:12:02 +00005452 ConstantInt::get(IntPtrTy, Size),
Chris Lattnere62f0212007-04-28 04:52:43 +00005453 GEP->getName()+".offs"), I);
5454 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005455 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005456
Owen Andersoneed707b2009-07-24 23:12:02 +00005457 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005458 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005459 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5460 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005461 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005462 Result = ConstantExpr::getAdd(RC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005463 else {
5464 // Emit an add instruction.
5465 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005466 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005467 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005468 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005469 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005470 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005471 // Convert to correct type.
5472 if (Op->getType() != IntPtrTy) {
5473 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005474 Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005475 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005476 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5477 true,
5478 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005479 }
5480 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005481 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattnere62f0212007-04-28 04:52:43 +00005482 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005483 Op = ConstantExpr::getMul(OpC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005484 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005485 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005486 GEP->getName()+".idx"), I);
5487 }
5488
5489 // Emit an add instruction.
5490 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005491 Result = ConstantExpr::getAdd(cast<Constant>(Op),
Chris Lattnere62f0212007-04-28 04:52:43 +00005492 cast<Constant>(Result));
5493 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005494 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005495 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005496 }
5497 return Result;
5498}
5499
Chris Lattner10c0d912008-04-22 02:53:33 +00005500
Dan Gohman8f080f02009-07-17 22:16:21 +00005501/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5502/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5503/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5504/// be complex, and scales are involved. The above expression would also be
5505/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5506/// This later form is less amenable to optimization though, and we are allowed
5507/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005508///
5509/// If we can't emit an optimized form for this expression, this returns null.
5510///
5511static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5512 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005513 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005514 gep_type_iterator GTI = gep_type_begin(GEP);
5515
5516 // Check to see if this gep only has a single variable index. If so, and if
5517 // any constant indices are a multiple of its scale, then we can compute this
5518 // in terms of the scale of the variable index. For example, if the GEP
5519 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5520 // because the expression will cross zero at the same point.
5521 unsigned i, e = GEP->getNumOperands();
5522 int64_t Offset = 0;
5523 for (i = 1; i != e; ++i, ++GTI) {
5524 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5525 // Compute the aggregate offset of constant indices.
5526 if (CI->isZero()) continue;
5527
5528 // Handle a struct index, which adds its field offset to the pointer.
5529 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5530 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5531 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005532 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005533 Offset += Size*CI->getSExtValue();
5534 }
5535 } else {
5536 // Found our variable index.
5537 break;
5538 }
5539 }
5540
5541 // If there are no variable indices, we must have a constant offset, just
5542 // evaluate it the general way.
5543 if (i == e) return 0;
5544
5545 Value *VariableIdx = GEP->getOperand(i);
5546 // Determine the scale factor of the variable element. For example, this is
5547 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005548 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005549
5550 // Verify that there are no other variable indices. If so, emit the hard way.
5551 for (++i, ++GTI; i != e; ++i, ++GTI) {
5552 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5553 if (!CI) return 0;
5554
5555 // Compute the aggregate offset of constant indices.
5556 if (CI->isZero()) continue;
5557
5558 // Handle a struct index, which adds its field offset to the pointer.
5559 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5560 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5561 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005562 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005563 Offset += Size*CI->getSExtValue();
5564 }
5565 }
5566
5567 // Okay, we know we have a single variable index, which must be a
5568 // pointer/array/vector index. If there is no offset, life is simple, return
5569 // the index.
5570 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5571 if (Offset == 0) {
5572 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5573 // we don't need to bother extending: the extension won't affect where the
5574 // computation crosses zero.
5575 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson1d0be152009-08-13 21:58:54 +00005576 VariableIdx = new TruncInst(VariableIdx,
5577 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005578 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005579 return VariableIdx;
5580 }
5581
5582 // Otherwise, there is an index. The computation we will do will be modulo
5583 // the pointer size, so get it.
5584 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5585
5586 Offset &= PtrSizeMask;
5587 VariableScale &= PtrSizeMask;
5588
5589 // To do this transformation, any constant index must be a multiple of the
5590 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5591 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5592 // multiple of the variable scale.
5593 int64_t NewOffs = Offset / (int64_t)VariableScale;
5594 if (Offset != NewOffs*(int64_t)VariableScale)
5595 return 0;
5596
5597 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson1d0be152009-08-13 21:58:54 +00005598 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner10c0d912008-04-22 02:53:33 +00005599 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005600 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005601 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005602 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005603 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005604 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005605}
5606
5607
Reid Spencere4d87aa2006-12-23 06:05:41 +00005608/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005609/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005610Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005611 ICmpInst::Predicate Cond,
5612 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005613 // Look through bitcasts.
5614 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5615 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005616
Chris Lattner574da9b2005-01-13 20:14:25 +00005617 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005618 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005619 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005620 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005621 // know pointers can't overflow since the gep is inbounds. See if we can
5622 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005623 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5624
5625 // If not, synthesize the offset the hard way.
5626 if (Offset == 0)
5627 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005628 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005629 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005630 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005631 // If the base pointers are different, but the indices are the same, just
5632 // compare the base pointer.
5633 if (PtrBase != GEPRHS->getOperand(0)) {
5634 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005635 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005636 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005637 if (IndicesTheSame)
5638 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5639 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5640 IndicesTheSame = false;
5641 break;
5642 }
5643
5644 // If all indices are the same, just compare the base pointers.
5645 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005646 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005647 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005648
5649 // Otherwise, the base pointers are different and the indices are
5650 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005651 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005652 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005653
Chris Lattnere9d782b2005-01-13 22:25:21 +00005654 // If one of the GEPs has all zero indices, recurse.
5655 bool AllZeros = true;
5656 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5657 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5658 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5659 AllZeros = false;
5660 break;
5661 }
5662 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005663 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5664 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005665
5666 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005667 AllZeros = true;
5668 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5669 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5670 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5671 AllZeros = false;
5672 break;
5673 }
5674 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005675 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005676
Chris Lattner4401c9c2005-01-14 00:20:05 +00005677 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5678 // If the GEPs only differ by one index, compare it.
5679 unsigned NumDifferences = 0; // Keep track of # differences.
5680 unsigned DiffOperand = 0; // The operand that differs.
5681 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5682 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005683 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5684 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005685 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005686 NumDifferences = 2;
5687 break;
5688 } else {
5689 if (NumDifferences++) break;
5690 DiffOperand = i;
5691 }
5692 }
5693
5694 if (NumDifferences == 0) // SAME GEP?
5695 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005696 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005697 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005698
Chris Lattner4401c9c2005-01-14 00:20:05 +00005699 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005700 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5701 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005702 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005703 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005704 }
5705 }
5706
Reid Spencere4d87aa2006-12-23 06:05:41 +00005707 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005708 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005709 if (TD &&
5710 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005711 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5712 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5713 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5714 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005715 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005716 }
5717 }
5718 return 0;
5719}
5720
Chris Lattnera5406232008-05-19 20:18:56 +00005721/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5722///
5723Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5724 Instruction *LHSI,
5725 Constant *RHSC) {
5726 if (!isa<ConstantFP>(RHSC)) return 0;
5727 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5728
5729 // Get the width of the mantissa. We don't want to hack on conversions that
5730 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005731 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005732 if (MantissaWidth == -1) return 0; // Unknown.
5733
5734 // Check to see that the input is converted from an integer type that is small
5735 // enough that preserves all bits. TODO: check here for "known" sign bits.
5736 // 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 +00005737 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005738
5739 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005740 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5741 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005742 ++InputSize;
5743
5744 // If the conversion would lose info, don't hack on this.
5745 if ((int)InputSize > MantissaWidth)
5746 return 0;
5747
5748 // Otherwise, we can potentially simplify the comparison. We know that it
5749 // will always come through as an integer value and we know the constant is
5750 // not a NAN (it would have been previously simplified).
5751 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5752
5753 ICmpInst::Predicate Pred;
5754 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005755 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005756 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005757 case FCmpInst::FCMP_OEQ:
5758 Pred = ICmpInst::ICMP_EQ;
5759 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005760 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005761 case FCmpInst::FCMP_OGT:
5762 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5763 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005764 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005765 case FCmpInst::FCMP_OGE:
5766 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5767 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005768 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005769 case FCmpInst::FCMP_OLT:
5770 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5771 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005772 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005773 case FCmpInst::FCMP_OLE:
5774 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5775 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005776 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005777 case FCmpInst::FCMP_ONE:
5778 Pred = ICmpInst::ICMP_NE;
5779 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005780 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005781 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005782 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005783 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005784 }
5785
5786 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5787
5788 // Now we know that the APFloat is a normal number, zero or inf.
5789
Chris Lattner85162782008-05-20 03:50:52 +00005790 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005791 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005792 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005793
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005794 if (!LHSUnsigned) {
5795 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5796 // and large values.
5797 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5798 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5799 APFloat::rmNearestTiesToEven);
5800 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5801 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5802 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005803 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5804 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005805 }
5806 } else {
5807 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5808 // +INF and large values.
5809 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5810 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5811 APFloat::rmNearestTiesToEven);
5812 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5813 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5814 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005815 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5816 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005817 }
Chris Lattnera5406232008-05-19 20:18:56 +00005818 }
5819
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005820 if (!LHSUnsigned) {
5821 // See if the RHS value is < SignedMin.
5822 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5823 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5824 APFloat::rmNearestTiesToEven);
5825 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5826 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5827 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005828 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5829 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005830 }
Chris Lattnera5406232008-05-19 20:18:56 +00005831 }
5832
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005833 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5834 // [0, UMAX], but it may still be fractional. See if it is fractional by
5835 // casting the FP value to the integer value and back, checking for equality.
5836 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005837 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005838 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5839 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005840 if (!RHS.isZero()) {
5841 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005842 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5843 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005844 if (!Equal) {
5845 // If we had a comparison against a fractional value, we have to adjust
5846 // the compare predicate and sometimes the value. RHSC is rounded towards
5847 // zero at this point.
5848 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005849 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005850 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005851 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005852 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005853 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005854 case ICmpInst::ICMP_ULE:
5855 // (float)int <= 4.4 --> int <= 4
5856 // (float)int <= -4.4 --> false
5857 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005858 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005859 break;
5860 case ICmpInst::ICMP_SLE:
5861 // (float)int <= 4.4 --> int <= 4
5862 // (float)int <= -4.4 --> int < -4
5863 if (RHS.isNegative())
5864 Pred = ICmpInst::ICMP_SLT;
5865 break;
5866 case ICmpInst::ICMP_ULT:
5867 // (float)int < -4.4 --> false
5868 // (float)int < 4.4 --> int <= 4
5869 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005870 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005871 Pred = ICmpInst::ICMP_ULE;
5872 break;
5873 case ICmpInst::ICMP_SLT:
5874 // (float)int < -4.4 --> int < -4
5875 // (float)int < 4.4 --> int <= 4
5876 if (!RHS.isNegative())
5877 Pred = ICmpInst::ICMP_SLE;
5878 break;
5879 case ICmpInst::ICMP_UGT:
5880 // (float)int > 4.4 --> int > 4
5881 // (float)int > -4.4 --> true
5882 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005883 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005884 break;
5885 case ICmpInst::ICMP_SGT:
5886 // (float)int > 4.4 --> int > 4
5887 // (float)int > -4.4 --> int >= -4
5888 if (RHS.isNegative())
5889 Pred = ICmpInst::ICMP_SGE;
5890 break;
5891 case ICmpInst::ICMP_UGE:
5892 // (float)int >= -4.4 --> true
5893 // (float)int >= 4.4 --> int > 4
5894 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005895 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005896 Pred = ICmpInst::ICMP_UGT;
5897 break;
5898 case ICmpInst::ICMP_SGE:
5899 // (float)int >= -4.4 --> int >= -4
5900 // (float)int >= 4.4 --> int > 4
5901 if (!RHS.isNegative())
5902 Pred = ICmpInst::ICMP_SGT;
5903 break;
5904 }
Chris Lattnera5406232008-05-19 20:18:56 +00005905 }
5906 }
5907
5908 // Lower this FP comparison into an appropriate integer version of the
5909 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005910 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005911}
5912
Reid Spencere4d87aa2006-12-23 06:05:41 +00005913Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5914 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005915 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005916
Chris Lattner58e97462007-01-14 19:42:17 +00005917 // Fold trivial predicates.
5918 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005919 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005920 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005921 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005922
5923 // Simplify 'fcmp pred X, X'
5924 if (Op0 == Op1) {
5925 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005926 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005927 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5928 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5929 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Anderson5defacc2009-07-31 17:39:07 +00005930 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005931 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5932 case FCmpInst::FCMP_OLT: // True if ordered and less than
5933 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Anderson5defacc2009-07-31 17:39:07 +00005934 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005935
5936 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5937 case FCmpInst::FCMP_ULT: // True if unordered or less than
5938 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5939 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5940 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5941 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005942 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005943 return &I;
5944
5945 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5946 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5947 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5948 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5949 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5950 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005951 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005952 return &I;
5953 }
5954 }
5955
Reid Spencere4d87aa2006-12-23 06:05:41 +00005956 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Anderson1d0be152009-08-13 21:58:54 +00005957 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
Chris Lattnere87597f2004-10-16 18:11:37 +00005958
Reid Spencere4d87aa2006-12-23 06:05:41 +00005959 // Handle fcmp with constant RHS
5960 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005961 // If the constant is a nan, see if we can fold the comparison based on it.
5962 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5963 if (CFP->getValueAPF().isNaN()) {
5964 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005965 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005966 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5967 "Comparison must be either ordered or unordered!");
5968 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005969 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005970 }
5971 }
5972
Reid Spencere4d87aa2006-12-23 06:05:41 +00005973 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5974 switch (LHSI->getOpcode()) {
5975 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005976 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5977 // block. If in the same block, we're encouraging jump threading. If
5978 // not, we are just pessimizing the code by making an i1 phi.
5979 if (LHSI->getParent() == I.getParent())
5980 if (Instruction *NV = FoldOpIntoPhi(I))
5981 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005982 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005983 case Instruction::SIToFP:
5984 case Instruction::UIToFP:
5985 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5986 return NV;
5987 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005988 case Instruction::Select:
5989 // If either operand of the select is a constant, we can fold the
5990 // comparison into the select arms, which will cause one to be
5991 // constant folded and the select turned into a bitwise or.
5992 Value *Op1 = 0, *Op2 = 0;
5993 if (LHSI->hasOneUse()) {
5994 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5995 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005996 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005997 // Insert a new FCmp of the other select operand.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005998 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005999 LHSI->getOperand(2), RHSC,
6000 I.getName()), I);
6001 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6002 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006003 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006004 // Insert a new FCmp of the other select operand.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006005 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006006 LHSI->getOperand(1), RHSC,
6007 I.getName()), I);
6008 }
6009 }
6010
6011 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006012 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006013 break;
6014 }
6015 }
6016
6017 return Changed ? &I : 0;
6018}
6019
6020Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
6021 bool Changed = SimplifyCompare(I);
6022 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6023 const Type *Ty = Op0->getType();
6024
6025 // icmp X, X
6026 if (Op0 == Op1)
Owen Anderson1d0be152009-08-13 21:58:54 +00006027 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006028 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00006029
6030 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Anderson1d0be152009-08-13 21:58:54 +00006031 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00006032
Reid Spencere4d87aa2006-12-23 06:05:41 +00006033 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00006034 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00006035 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
6036 isa<ConstantPointerNull>(Op0)) &&
6037 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00006038 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00006039 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006040 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00006041
Reid Spencere4d87aa2006-12-23 06:05:41 +00006042 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00006043 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006044 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006045 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006046 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006047 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00006048 InsertNewInstBefore(Xor, I);
Dan Gohman4ae51262009-08-12 16:23:25 +00006049 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006050 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006051 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006052 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006053
Reid Spencere4d87aa2006-12-23 06:05:41 +00006054 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006055 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006056 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006057 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Dan Gohman4ae51262009-08-12 16:23:25 +00006058 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006059 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006060 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006061 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006062 case ICmpInst::ICMP_SGT:
6063 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006064 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006065 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Dan Gohman4ae51262009-08-12 16:23:25 +00006066 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006067 InsertNewInstBefore(Not, I);
6068 return BinaryOperator::CreateAnd(Not, Op0);
6069 }
6070 case ICmpInst::ICMP_UGE:
6071 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6072 // FALL THROUGH
6073 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Dan Gohman4ae51262009-08-12 16:23:25 +00006074 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006075 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006076 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006077 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006078 case ICmpInst::ICMP_SGE:
6079 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6080 // FALL THROUGH
6081 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Dan Gohman4ae51262009-08-12 16:23:25 +00006082 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006083 InsertNewInstBefore(Not, I);
6084 return BinaryOperator::CreateOr(Not, Op0);
6085 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006086 }
Chris Lattner8b170942002-08-09 23:47:40 +00006087 }
6088
Dan Gohman1c8491e2009-04-25 17:12:48 +00006089 unsigned BitWidth = 0;
6090 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006091 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6092 else if (Ty->isIntOrIntVector())
6093 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006094
6095 bool isSignBit = false;
6096
Dan Gohman81b28ce2008-09-16 18:46:06 +00006097 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006098 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006099 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006100
Chris Lattnerb6566012008-01-05 01:18:20 +00006101 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6102 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006103 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006104 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006105 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006106 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006107
Dan Gohman81b28ce2008-09-16 18:46:06 +00006108 // If we have an icmp le or icmp ge instruction, turn it into the
6109 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6110 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006111 switch (I.getPredicate()) {
6112 default: break;
6113 case ICmpInst::ICMP_ULE:
6114 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006115 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006116 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006117 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006118 case ICmpInst::ICMP_SLE:
6119 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006120 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006121 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006122 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006123 case ICmpInst::ICMP_UGE:
6124 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006125 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006126 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006127 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006128 case ICmpInst::ICMP_SGE:
6129 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006130 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006131 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006132 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006133 }
6134
Chris Lattner183661e2008-07-11 05:40:05 +00006135 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006136 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006137 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006138 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6139 }
6140
6141 // See if we can fold the comparison based on range information we can get
6142 // by checking whether bits are known to be zero or one in the input.
6143 if (BitWidth != 0) {
6144 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6145 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6146
6147 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006148 isSignBit ? APInt::getSignBit(BitWidth)
6149 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006150 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006151 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006152 if (SimplifyDemandedBits(I.getOperandUse(1),
6153 APInt::getAllOnesValue(BitWidth),
6154 Op1KnownZero, Op1KnownOne, 0))
6155 return &I;
6156
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006157 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006158 // in. Compute the Min, Max and RHS values based on the known bits. For the
6159 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006160 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6161 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6162 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6163 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6164 Op0Min, Op0Max);
6165 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6166 Op1Min, Op1Max);
6167 } else {
6168 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6169 Op0Min, Op0Max);
6170 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6171 Op1Min, Op1Max);
6172 }
6173
Chris Lattner183661e2008-07-11 05:40:05 +00006174 // If Min and Max are known to be the same, then SimplifyDemandedBits
6175 // figured out that the LHS is a constant. Just constant fold this now so
6176 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006177 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006178 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006179 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006180 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006181 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006182 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006183
Chris Lattner183661e2008-07-11 05:40:05 +00006184 // Based on the range information we know about the LHS, see if we can
6185 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006186 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006187 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006188 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006189 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006190 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006191 break;
6192 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006193 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006194 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006195 break;
6196 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006197 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006198 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006199 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006200 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006201 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006202 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006203 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6204 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006205 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006206 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006207
6208 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6209 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006210 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006211 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006212 }
Chris Lattner84dff672008-07-11 05:08:55 +00006213 break;
6214 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006215 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006216 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006217 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006218 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006219
6220 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006221 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006222 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6223 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006224 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006225 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006226
6227 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6228 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006229 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006230 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006231 }
Chris Lattner84dff672008-07-11 05:08:55 +00006232 break;
6233 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006234 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006235 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006236 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006237 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006238 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006239 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006240 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6241 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006242 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006243 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006244 }
Chris Lattner84dff672008-07-11 05:08:55 +00006245 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006246 case ICmpInst::ICMP_SGT:
6247 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006248 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006249 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006250 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006251
6252 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006253 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006254 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6255 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006256 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006257 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006258 }
6259 break;
6260 case ICmpInst::ICMP_SGE:
6261 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6262 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006263 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006264 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006265 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006266 break;
6267 case ICmpInst::ICMP_SLE:
6268 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6269 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006270 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006271 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006272 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006273 break;
6274 case ICmpInst::ICMP_UGE:
6275 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6276 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006277 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006278 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006279 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006280 break;
6281 case ICmpInst::ICMP_ULE:
6282 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6283 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006284 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006285 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006286 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006287 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006288 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006289
6290 // Turn a signed comparison into an unsigned one if both operands
6291 // are known to have the same sign.
6292 if (I.isSignedPredicate() &&
6293 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6294 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006295 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006296 }
6297
6298 // Test if the ICmpInst instruction is used exclusively by a select as
6299 // part of a minimum or maximum operation. If so, refrain from doing
6300 // any other folding. This helps out other analyses which understand
6301 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6302 // and CodeGen. And in this case, at least one of the comparison
6303 // operands has at least one user besides the compare (the select),
6304 // which would often largely negate the benefit of folding anyway.
6305 if (I.hasOneUse())
6306 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6307 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6308 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6309 return 0;
6310
6311 // See if we are doing a comparison between a constant and an instruction that
6312 // can be folded into the comparison.
6313 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006314 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006315 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006316 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006317 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006318 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6319 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006320 }
6321
Chris Lattner01deb9d2007-04-03 17:43:25 +00006322 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006323 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6324 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6325 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006326 case Instruction::GetElementPtr:
6327 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006328 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006329 bool isAllZeros = true;
6330 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6331 if (!isa<Constant>(LHSI->getOperand(i)) ||
6332 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6333 isAllZeros = false;
6334 break;
6335 }
6336 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006337 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006338 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006339 }
6340 break;
6341
Chris Lattner6970b662005-04-23 15:31:55 +00006342 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006343 // Only fold icmp into the PHI if the phi and fcmp are in the same
6344 // block. If in the same block, we're encouraging jump threading. If
6345 // not, we are just pessimizing the code by making an i1 phi.
6346 if (LHSI->getParent() == I.getParent())
6347 if (Instruction *NV = FoldOpIntoPhi(I))
6348 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006349 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006350 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006351 // If either operand of the select is a constant, we can fold the
6352 // comparison into the select arms, which will cause one to be
6353 // constant folded and the select turned into a bitwise or.
6354 Value *Op1 = 0, *Op2 = 0;
6355 if (LHSI->hasOneUse()) {
6356 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6357 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006358 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006359 // Insert a new ICmp of the other select operand.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006360 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006361 LHSI->getOperand(2), RHSC,
6362 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006363 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6364 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006365 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006366 // Insert a new ICmp of the other select operand.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006367 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006368 LHSI->getOperand(1), RHSC,
6369 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006370 }
6371 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006372
Chris Lattner6970b662005-04-23 15:31:55 +00006373 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006374 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006375 break;
6376 }
Chris Lattner4802d902007-04-06 18:57:34 +00006377 case Instruction::Malloc:
6378 // If we have (malloc != null), and if the malloc has a single use, we
6379 // can assume it is successful and remove the malloc.
6380 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6381 AddToWorkList(LHSI);
Owen Anderson1d0be152009-08-13 21:58:54 +00006382 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006383 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006384 }
6385 break;
6386 }
Chris Lattner6970b662005-04-23 15:31:55 +00006387 }
6388
Reid Spencere4d87aa2006-12-23 06:05:41 +00006389 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006390 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006391 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006392 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006393 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006394 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6395 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006396 return NI;
6397
Reid Spencere4d87aa2006-12-23 06:05:41 +00006398 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006399 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6400 // now.
6401 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6402 if (isa<PointerType>(Op0->getType()) &&
6403 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006404 // We keep moving the cast from the left operand over to the right
6405 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006406 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006407
Chris Lattner57d86372007-01-06 01:45:59 +00006408 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6409 // so eliminate it as well.
6410 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6411 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006412
Chris Lattnerde90b762003-11-03 04:25:02 +00006413 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006414 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006415 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006416 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006417 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006418 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006419 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006420 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006421 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006422 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006423 }
Chris Lattner57d86372007-01-06 01:45:59 +00006424 }
6425
6426 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006427 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006428 // This comes up when you have code like
6429 // int X = A < B;
6430 // if (X) ...
6431 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006432 // with a constant or another cast from the same type.
6433 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006434 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006435 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006436 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006437
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006438 // See if it's the same type of instruction on the left and right.
6439 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6440 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006441 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006442 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006443 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006444 default: break;
6445 case Instruction::Add:
6446 case Instruction::Sub:
6447 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006448 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006449 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006450 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006451 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6452 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6453 if (CI->getValue().isSignBit()) {
6454 ICmpInst::Predicate Pred = I.isSignedPredicate()
6455 ? I.getUnsignedPredicate()
6456 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006457 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006458 Op1I->getOperand(0));
6459 }
6460
6461 if (CI->getValue().isMaxSignedValue()) {
6462 ICmpInst::Predicate Pred = I.isSignedPredicate()
6463 ? I.getUnsignedPredicate()
6464 : I.getSignedPredicate();
6465 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006466 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006467 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006468 }
6469 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006470 break;
6471 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006472 if (!I.isEquality())
6473 break;
6474
Nick Lewycky5d52c452008-08-21 05:56:10 +00006475 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6476 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6477 // Mask = -1 >> count-trailing-zeros(Cst).
6478 if (!CI->isZero() && !CI->isOne()) {
6479 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006480 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006481 APInt::getLowBitsSet(AP.getBitWidth(),
6482 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006483 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006484 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6485 Mask);
6486 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6487 Mask);
6488 InsertNewInstBefore(And1, I);
6489 InsertNewInstBefore(And2, I);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006490 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006491 }
6492 }
6493 break;
6494 }
6495 }
6496 }
6497 }
6498
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006499 // ~x < ~y --> y < x
6500 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006501 if (match(Op0, m_Not(m_Value(A))) &&
6502 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006503 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006504 }
6505
Chris Lattner65b72ba2006-09-18 04:22:48 +00006506 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006507 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006508
6509 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006510 if (match(Op0, m_Neg(m_Value(A))) &&
6511 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006512 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006513
Dan Gohman4ae51262009-08-12 16:23:25 +00006514 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006515 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6516 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006517 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006518 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006519 }
6520
Dan Gohman4ae51262009-08-12 16:23:25 +00006521 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006522 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006523 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006524 if (match(B, m_ConstantInt(C1)) &&
6525 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006526 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006527 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattnercb504b92008-11-16 05:38:51 +00006528 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006529 return new ICmpInst(I.getPredicate(), A,
Chris Lattnercb504b92008-11-16 05:38:51 +00006530 InsertNewInstBefore(Xor, I));
6531 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006532
6533 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006534 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6535 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6536 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6537 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006538 }
6539 }
6540
Dan Gohman4ae51262009-08-12 16:23:25 +00006541 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006542 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006543 // A == (A^B) -> B == 0
6544 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006545 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006546 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006547 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006548
6549 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006550 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006551 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006552 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006553
6554 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006555 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006556 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006557 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006558
Chris Lattner9c2328e2006-11-14 06:06:06 +00006559 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6560 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006561 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6562 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006563 Value *X = 0, *Y = 0, *Z = 0;
6564
6565 if (A == C) {
6566 X = B; Y = D; Z = A;
6567 } else if (A == D) {
6568 X = B; Y = C; Z = A;
6569 } else if (B == C) {
6570 X = A; Y = D; Z = B;
6571 } else if (B == D) {
6572 X = A; Y = C; Z = B;
6573 }
6574
6575 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006576 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6577 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006578 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006579 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006580 return &I;
6581 }
6582 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006583 }
Chris Lattner7e708292002-06-25 16:13:24 +00006584 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006585}
6586
Chris Lattner562ef782007-06-20 23:46:26 +00006587
6588/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6589/// and CmpRHS are both known to be integer constants.
6590Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6591 ConstantInt *DivRHS) {
6592 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6593 const APInt &CmpRHSV = CmpRHS->getValue();
6594
6595 // FIXME: If the operand types don't match the type of the divide
6596 // then don't attempt this transform. The code below doesn't have the
6597 // logic to deal with a signed divide and an unsigned compare (and
6598 // vice versa). This is because (x /s C1) <s C2 produces different
6599 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6600 // (x /u C1) <u C2. Simply casting the operands and result won't
6601 // work. :( The if statement below tests that condition and bails
6602 // if it finds it.
6603 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6604 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6605 return 0;
6606 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006607 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006608 if (DivIsSigned && DivRHS->isAllOnesValue())
6609 return 0; // The overflow computation also screws up here
6610 if (DivRHS->isOne())
6611 return 0; // Not worth bothering, and eliminates some funny cases
6612 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006613
6614 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6615 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6616 // C2 (CI). By solving for X we can turn this into a range check
6617 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006618 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006619
6620 // Determine if the product overflows by seeing if the product is
6621 // not equal to the divide. Make sure we do the same kind of divide
6622 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006623 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6624 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006625
6626 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006627 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006628
Chris Lattner1dbfd482007-06-21 18:11:19 +00006629 // Figure out the interval that is being checked. For example, a comparison
6630 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6631 // Compute this interval based on the constants involved and the signedness of
6632 // the compare/divide. This computes a half-open interval, keeping track of
6633 // whether either value in the interval overflows. After analysis each
6634 // overflow variable is set to 0 if it's corresponding bound variable is valid
6635 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6636 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006637 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006638
Chris Lattner562ef782007-06-20 23:46:26 +00006639 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006640 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006641 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006642 HiOverflow = LoOverflow = ProdOV;
6643 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006644 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006645 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006646 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006647 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006648 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006649 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006650 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006651 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6652 HiOverflow = LoOverflow = ProdOV;
6653 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006654 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006655 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006656 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006657 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006658 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6659 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006660 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006661 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006662 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006663 true) ? -1 : 0;
6664 }
Chris Lattner562ef782007-06-20 23:46:26 +00006665 }
Dan Gohman76491272008-02-13 22:09:18 +00006666 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006667 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006668 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006669 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006670 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006671 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6672 HiOverflow = 1; // [INTMIN+1, overflow)
6673 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6674 }
Dan Gohman76491272008-02-13 22:09:18 +00006675 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006676 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006677 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006678 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006679 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006680 LoOverflow = AddWithOverflow(LoBound, HiBound,
6681 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006682 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006683 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6684 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006685 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006686 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006687 }
6688
Chris Lattner1dbfd482007-06-21 18:11:19 +00006689 // Dividing by a negative swaps the condition. LT <-> GT
6690 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006691 }
6692
6693 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006694 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006695 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006696 case ICmpInst::ICMP_EQ:
6697 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006698 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006699 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006700 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006701 ICmpInst::ICMP_UGE, X, LoBound);
6702 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006703 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006704 ICmpInst::ICMP_ULT, X, HiBound);
6705 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006706 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006707 case ICmpInst::ICMP_NE:
6708 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006709 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006710 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006711 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006712 ICmpInst::ICMP_ULT, X, LoBound);
6713 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006714 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006715 ICmpInst::ICMP_UGE, X, HiBound);
6716 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006717 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006718 case ICmpInst::ICMP_ULT:
6719 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006720 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006721 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006722 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006723 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006724 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006725 case ICmpInst::ICMP_UGT:
6726 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006727 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006728 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006729 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006730 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006731 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006732 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006733 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006734 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006735 }
6736}
6737
6738
Chris Lattner01deb9d2007-04-03 17:43:25 +00006739/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6740///
6741Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6742 Instruction *LHSI,
6743 ConstantInt *RHS) {
6744 const APInt &RHSV = RHS->getValue();
6745
6746 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006747 case Instruction::Trunc:
6748 if (ICI.isEquality() && LHSI->hasOneUse()) {
6749 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6750 // of the high bits truncated out of x are known.
6751 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6752 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6753 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6754 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6755 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6756
6757 // If all the high bits are known, we can do this xform.
6758 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6759 // Pull in the high bits from known-ones set.
6760 APInt NewRHS(RHS->getValue());
6761 NewRHS.zext(SrcBits);
6762 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006763 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006764 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006765 }
6766 }
6767 break;
6768
Duncan Sands0091bf22007-04-04 06:42:45 +00006769 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006770 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6771 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6772 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006773 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6774 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006775 Value *CompareVal = LHSI->getOperand(0);
6776
6777 // If the sign bit of the XorCST is not set, there is no change to
6778 // the operation, just stop using the Xor.
6779 if (!XorCST->getValue().isNegative()) {
6780 ICI.setOperand(0, CompareVal);
6781 AddToWorkList(LHSI);
6782 return &ICI;
6783 }
6784
6785 // Was the old condition true if the operand is positive?
6786 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6787
6788 // If so, the new one isn't.
6789 isTrueIfPositive ^= true;
6790
6791 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006792 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006793 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006794 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006795 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006796 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006797 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006798
6799 if (LHSI->hasOneUse()) {
6800 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6801 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6802 const APInt &SignBit = XorCST->getValue();
6803 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6804 ? ICI.getUnsignedPredicate()
6805 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006806 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006807 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006808 }
6809
6810 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006811 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006812 const APInt &NotSignBit = XorCST->getValue();
6813 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6814 ? ICI.getUnsignedPredicate()
6815 : ICI.getSignedPredicate();
6816 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006817 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006818 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006819 }
6820 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006821 }
6822 break;
6823 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6824 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6825 LHSI->getOperand(0)->hasOneUse()) {
6826 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6827
6828 // If the LHS is an AND of a truncating cast, we can widen the
6829 // and/compare to be the input width without changing the value
6830 // produced, eliminating a cast.
6831 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6832 // We can do this transformation if either the AND constant does not
6833 // have its sign bit set or if it is an equality comparison.
6834 // Extending a relational comparison when we're checking the sign
6835 // bit would not work.
6836 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006837 (ICI.isEquality() ||
6838 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006839 uint32_t BitWidth =
6840 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6841 APInt NewCST = AndCST->getValue();
6842 NewCST.zext(BitWidth);
6843 APInt NewCI = RHSV;
6844 NewCI.zext(BitWidth);
6845 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006846 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006847 ConstantInt::get(*Context, NewCST), LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006848 InsertNewInstBefore(NewAnd, ICI);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006849 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006850 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006851 }
6852 }
6853
6854 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6855 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6856 // happens a LOT in code produced by the C front-end, for bitfield
6857 // access.
6858 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6859 if (Shift && !Shift->isShift())
6860 Shift = 0;
6861
6862 ConstantInt *ShAmt;
6863 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6864 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6865 const Type *AndTy = AndCST->getType(); // Type of the and.
6866
6867 // We can fold this as long as we can't shift unknown bits
6868 // into the mask. This can only happen with signed shift
6869 // rights, as they sign-extend.
6870 if (ShAmt) {
6871 bool CanFold = Shift->isLogicalShift();
6872 if (!CanFold) {
6873 // To test for the bad case of the signed shr, see if any
6874 // of the bits shifted in could be tested after the mask.
6875 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6876 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6877
6878 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6879 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6880 AndCST->getValue()) == 0)
6881 CanFold = true;
6882 }
6883
6884 if (CanFold) {
6885 Constant *NewCst;
6886 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006887 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006888 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006889 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006890
6891 // Check to see if we are shifting out any of the bits being
6892 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006893 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006894 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006895 // If we shifted bits out, the fold is not going to work out.
6896 // As a special case, check to see if this means that the
6897 // result is always true or false now.
6898 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006899 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006900 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006901 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006902 } else {
6903 ICI.setOperand(1, NewCst);
6904 Constant *NewAndCST;
6905 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006906 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006907 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006908 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006909 LHSI->setOperand(1, NewAndCST);
6910 LHSI->setOperand(0, Shift->getOperand(0));
6911 AddToWorkList(Shift); // Shift is dead.
6912 AddUsesToWorkList(ICI);
6913 return &ICI;
6914 }
6915 }
6916 }
6917
6918 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6919 // preferable because it allows the C<<Y expression to be hoisted out
6920 // of a loop if Y is invariant and X is not.
6921 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006922 ICI.isEquality() && !Shift->isArithmeticShift() &&
6923 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006924 // Compute C << Y.
6925 Value *NS;
6926 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006927 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006928 Shift->getOperand(1), "tmp");
6929 } else {
6930 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006931 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006932 Shift->getOperand(1), "tmp");
6933 }
6934 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6935
6936 // Compute X & (C << Y).
6937 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006938 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006939 InsertNewInstBefore(NewAnd, ICI);
6940
6941 ICI.setOperand(0, NewAnd);
6942 return &ICI;
6943 }
6944 }
6945 break;
6946
Chris Lattnera0141b92007-07-15 20:42:37 +00006947 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6948 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6949 if (!ShAmt) break;
6950
6951 uint32_t TypeBits = RHSV.getBitWidth();
6952
6953 // Check that the shift amount is in range. If not, don't perform
6954 // undefined shifts. When the shift is visited it will be
6955 // simplified.
6956 if (ShAmt->uge(TypeBits))
6957 break;
6958
6959 if (ICI.isEquality()) {
6960 // If we are comparing against bits always shifted out, the
6961 // comparison cannot succeed.
6962 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006963 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006964 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006965 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6966 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006967 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006968 return ReplaceInstUsesWith(ICI, Cst);
6969 }
6970
6971 if (LHSI->hasOneUse()) {
6972 // Otherwise strength reduce the shift into an and.
6973 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6974 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006975 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006976 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006977
Chris Lattnera0141b92007-07-15 20:42:37 +00006978 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006979 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006980 Mask, LHSI->getName()+".mask");
6981 Value *And = InsertNewInstBefore(AndI, ICI);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006982 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006983 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006984 }
6985 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006986
6987 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6988 bool TrueIfSigned = false;
6989 if (LHSI->hasOneUse() &&
6990 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6991 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006992 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006993 (TypeBits-ShAmt->getZExtValue()-1));
6994 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006995 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006996 Mask, LHSI->getName()+".mask");
6997 Value *And = InsertNewInstBefore(AndI, ICI);
6998
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006999 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00007000 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00007001 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007002 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007003 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007004
7005 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00007006 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007007 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00007008 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007009 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007010
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007011 // Check that the shift amount is in range. If not, don't perform
7012 // undefined shifts. When the shift is visited it will be
7013 // simplified.
7014 uint32_t TypeBits = RHSV.getBitWidth();
7015 if (ShAmt->uge(TypeBits))
7016 break;
7017
7018 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00007019
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007020 // If we are comparing against bits always shifted out, the
7021 // comparison cannot succeed.
7022 APInt Comp = RHSV << ShAmtVal;
7023 if (LHSI->getOpcode() == Instruction::LShr)
7024 Comp = Comp.lshr(ShAmtVal);
7025 else
7026 Comp = Comp.ashr(ShAmtVal);
7027
7028 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7029 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007030 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007031 return ReplaceInstUsesWith(ICI, Cst);
7032 }
7033
7034 // Otherwise, check to see if the bits shifted out are known to be zero.
7035 // If so, we can compare against the unshifted value:
7036 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007037 if (LHSI->hasOneUse() &&
7038 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007039 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007040 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007041 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007042 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007043
Evan Chengf30752c2008-04-23 00:38:06 +00007044 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007045 // Otherwise strength reduce the shift into an and.
7046 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007047 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007048
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007049 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007050 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007051 Mask, LHSI->getName()+".mask");
7052 Value *And = InsertNewInstBefore(AndI, ICI);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007053 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007054 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007055 }
7056 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007057 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007058
7059 case Instruction::SDiv:
7060 case Instruction::UDiv:
7061 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7062 // Fold this div into the comparison, producing a range check.
7063 // Determine, based on the divide type, what the range is being
7064 // checked. If there is an overflow on the low or high side, remember
7065 // it, otherwise compute the range [low, hi) bounding the new value.
7066 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007067 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7068 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7069 DivRHS))
7070 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007071 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007072
7073 case Instruction::Add:
7074 // Fold: icmp pred (add, X, C1), C2
7075
7076 if (!ICI.isEquality()) {
7077 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7078 if (!LHSC) break;
7079 const APInt &LHSV = LHSC->getValue();
7080
7081 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7082 .subtract(LHSV);
7083
7084 if (ICI.isSignedPredicate()) {
7085 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007086 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007087 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007088 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007089 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007090 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007091 }
7092 } else {
7093 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007094 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007095 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007096 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007097 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007098 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007099 }
7100 }
7101 }
7102 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007103 }
7104
7105 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7106 if (ICI.isEquality()) {
7107 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7108
7109 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7110 // the second operand is a constant, simplify a bit.
7111 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7112 switch (BO->getOpcode()) {
7113 case Instruction::SRem:
7114 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7115 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7116 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7117 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7118 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007119 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007120 BO->getName());
7121 InsertNewInstBefore(NewRem, ICI);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007122 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007123 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007124 }
7125 }
7126 break;
7127 case Instruction::Add:
7128 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7129 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7130 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007131 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007132 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007133 } else if (RHSV == 0) {
7134 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7135 // efficiently invertible, or if the add has just this one use.
7136 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7137
Dan Gohman186a6362009-08-12 16:04:34 +00007138 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007139 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007140 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007141 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007142 else if (BO->hasOneUse()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00007143 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007144 InsertNewInstBefore(Neg, ICI);
7145 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007146 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007147 }
7148 }
7149 break;
7150 case Instruction::Xor:
7151 // For the xor case, we can xor two constants together, eliminating
7152 // the explicit xor.
7153 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007154 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007155 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007156
7157 // FALLTHROUGH
7158 case Instruction::Sub:
7159 // Replace (([sub|xor] A, B) != 0) with (A != B)
7160 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007161 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007162 BO->getOperand(1));
7163 break;
7164
7165 case Instruction::Or:
7166 // If bits are being or'd in that are not present in the constant we
7167 // are comparing against, then the comparison could never succeed!
7168 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007169 Constant *NotCI = ConstantExpr::getNot(RHS);
7170 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007171 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007172 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007173 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007174 }
7175 break;
7176
7177 case Instruction::And:
7178 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7179 // If bits are being compared against that are and'd out, then the
7180 // comparison can never succeed!
7181 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007182 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007183 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007184 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007185
7186 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7187 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007188 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007189 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007190 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007191
7192 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007193 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007194 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007195 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007196 ICmpInst::Predicate pred = isICMP_NE ?
7197 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007198 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007199 }
7200
7201 // ((X & ~7) == 0) --> X < 8
7202 if (RHSV == 0 && isHighOnes(BOC)) {
7203 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007204 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007205 ICmpInst::Predicate pred = isICMP_NE ?
7206 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007207 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007208 }
7209 }
7210 default: break;
7211 }
7212 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7213 // Handle icmp {eq|ne} <intrinsic>, intcst.
7214 if (II->getIntrinsicID() == Intrinsic::bswap) {
7215 AddToWorkList(II);
7216 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007217 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007218 return &ICI;
7219 }
7220 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007221 }
7222 return 0;
7223}
7224
7225/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7226/// We only handle extending casts so far.
7227///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007228Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7229 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007230 Value *LHSCIOp = LHSCI->getOperand(0);
7231 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007232 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007233 Value *RHSCIOp;
7234
Chris Lattner8c756c12007-05-05 22:41:33 +00007235 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7236 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007237 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7238 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007239 cast<IntegerType>(DestTy)->getBitWidth()) {
7240 Value *RHSOp = 0;
7241 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007242 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007243 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7244 RHSOp = RHSC->getOperand(0);
7245 // If the pointer types don't match, insert a bitcast.
7246 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007247 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007248 }
7249
7250 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007251 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007252 }
7253
7254 // The code below only handles extension cast instructions, so far.
7255 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007256 if (LHSCI->getOpcode() != Instruction::ZExt &&
7257 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007258 return 0;
7259
Reid Spencere4d87aa2006-12-23 06:05:41 +00007260 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7261 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007262
Reid Spencere4d87aa2006-12-23 06:05:41 +00007263 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007264 // Not an extension from the same type?
7265 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007266 if (RHSCIOp->getType() != LHSCIOp->getType())
7267 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007268
Nick Lewycky4189a532008-01-28 03:48:02 +00007269 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007270 // and the other is a zext), then we can't handle this.
7271 if (CI->getOpcode() != LHSCI->getOpcode())
7272 return 0;
7273
Nick Lewycky4189a532008-01-28 03:48:02 +00007274 // Deal with equality cases early.
7275 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007276 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007277
7278 // A signed comparison of sign extended values simplifies into a
7279 // signed comparison.
7280 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007281 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007282
7283 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007284 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007285 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007286
Reid Spencere4d87aa2006-12-23 06:05:41 +00007287 // If we aren't dealing with a constant on the RHS, exit early
7288 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7289 if (!CI)
7290 return 0;
7291
7292 // Compute the constant that would happen if we truncated to SrcTy then
7293 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007294 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7295 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007296 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007297
7298 // If the re-extended constant didn't change...
7299 if (Res2 == CI) {
7300 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7301 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007302 // %A = sext i16 %X to i32
7303 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007304 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007305 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007306 // because %A may have negative value.
7307 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007308 // However, we allow this when the compare is EQ/NE, because they are
7309 // signless.
7310 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007311 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007312 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007313 }
7314
7315 // The re-extended constant changed so the constant cannot be represented
7316 // in the shorter type. Consequently, we cannot emit a simple comparison.
7317
7318 // First, handle some easy cases. We know the result cannot be equal at this
7319 // point so handle the ICI.isEquality() cases
7320 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007321 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007322 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007323 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007324
7325 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7326 // should have been folded away previously and not enter in here.
7327 Value *Result;
7328 if (isSignedCmp) {
7329 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007330 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007331 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007332 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007333 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007334 } else {
7335 // We're performing an unsigned comparison.
7336 if (isSignedExt) {
7337 // We're performing an unsigned comp with a sign extended value.
7338 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007339 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007340 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT,
Owen Anderson333c4002009-07-09 23:48:35 +00007341 LHSCIOp, NegOne, ICI.getName()), ICI);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007342 } else {
7343 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007344 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007345 }
7346 }
7347
7348 // Finally, return the value computed.
7349 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007350 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007351 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007352
7353 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7354 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7355 "ICmp should be folded!");
7356 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007357 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007358 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007359}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007360
Reid Spencer832254e2007-02-02 02:16:23 +00007361Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7362 return commonShiftTransforms(I);
7363}
7364
7365Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7366 return commonShiftTransforms(I);
7367}
7368
7369Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007370 if (Instruction *R = commonShiftTransforms(I))
7371 return R;
7372
7373 Value *Op0 = I.getOperand(0);
7374
7375 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7376 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7377 if (CSI->isAllOnesValue())
7378 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007379
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007380 // See if we can turn a signed shr into an unsigned shr.
7381 if (MaskedValueIsZero(Op0,
7382 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7383 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7384
7385 // Arithmetic shifting an all-sign-bit value is a no-op.
7386 unsigned NumSignBits = ComputeNumSignBits(Op0);
7387 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7388 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007389
Chris Lattner348f6652007-12-06 01:59:46 +00007390 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007391}
7392
7393Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7394 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007395 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007396
7397 // shl X, 0 == X and shr X, 0 == X
7398 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007399 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7400 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007401 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007402
Reid Spencere4d87aa2006-12-23 06:05:41 +00007403 if (isa<UndefValue>(Op0)) {
7404 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007405 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007406 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007407 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007408 }
7409 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007410 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7411 return ReplaceInstUsesWith(I, Op0);
7412 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007413 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007414 }
7415
Dan Gohman9004c8a2009-05-21 02:28:33 +00007416 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007417 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007418 return &I;
7419
Chris Lattner2eefe512004-04-09 19:05:30 +00007420 // Try to fold constant and into select arguments.
7421 if (isa<Constant>(Op0))
7422 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007423 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007424 return R;
7425
Reid Spencerb83eb642006-10-20 07:07:24 +00007426 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007427 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7428 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007429 return 0;
7430}
7431
Reid Spencerb83eb642006-10-20 07:07:24 +00007432Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007433 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007434 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007435
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007436 // See if we can simplify any instructions used by the instruction whose sole
7437 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007438 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007439
Dan Gohmana119de82009-06-14 23:30:43 +00007440 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7441 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007442 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007443 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007444 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007445 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007446 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007447 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007448 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007449 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007450 }
7451
7452 // ((X*C1) << C2) == (X * (C1 << C2))
7453 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7454 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7455 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007456 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007457 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007458
7459 // Try to fold constant and into select arguments.
7460 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7461 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7462 return R;
7463 if (isa<PHINode>(Op0))
7464 if (Instruction *NV = FoldOpIntoPhi(I))
7465 return NV;
7466
Chris Lattner8999dd32007-12-22 09:07:47 +00007467 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7468 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7469 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7470 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7471 // place. Don't try to do this transformation in this case. Also, we
7472 // require that the input operand is a shift-by-constant so that we have
7473 // confidence that the shifts will get folded together. We could do this
7474 // xform in more cases, but it is unlikely to be profitable.
7475 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7476 isa<ConstantInt>(TrOp->getOperand(1))) {
7477 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007478 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007479 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007480 I.getName());
7481 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7482
7483 // For logical shifts, the truncation has the effect of making the high
7484 // part of the register be zeros. Emulate this by inserting an AND to
7485 // clear the top bits as needed. This 'and' will usually be zapped by
7486 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007487 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7488 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007489 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7490
7491 // The mask we constructed says what the trunc would do if occurring
7492 // between the shifts. We want to know the effect *after* the second
7493 // shift. We know that it is a logical shift by a constant, so adjust the
7494 // mask as appropriate.
7495 if (I.getOpcode() == Instruction::Shl)
7496 MaskV <<= Op1->getZExtValue();
7497 else {
7498 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7499 MaskV = MaskV.lshr(Op1->getZExtValue());
7500 }
7501
Owen Andersond672ecb2009-07-03 00:17:18 +00007502 Instruction *And =
Owen Andersoneed707b2009-07-24 23:12:02 +00007503 BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
Owen Andersond672ecb2009-07-03 00:17:18 +00007504 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007505 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7506
7507 // Return the value truncated to the interesting size.
7508 return new TruncInst(And, I.getType());
7509 }
7510 }
7511
Chris Lattner4d5542c2006-01-06 07:12:35 +00007512 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007513 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7514 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7515 Value *V1, *V2;
7516 ConstantInt *CC;
7517 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007518 default: break;
7519 case Instruction::Add:
7520 case Instruction::And:
7521 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007522 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007523 // These operators commute.
7524 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007525 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007526 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007527 m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007528 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007529 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007530 Op0BO->getName());
7531 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007532 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007533 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007534 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007535 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007536 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007537 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007538 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007539 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007540
Chris Lattner150f12a2005-09-18 06:30:59 +00007541 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007542 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007543 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007544 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007545 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007546 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007547 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007548 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007549 Op0BO->getOperand(0), Op1,
7550 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007551 InsertNewInstBefore(YS, I); // (Y << C)
7552 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007553 BinaryOperator::CreateAnd(V1,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007554 ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007555 V1->getName()+".mask");
7556 InsertNewInstBefore(XM, I); // X & (CC << C)
7557
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007558 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007559 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007560 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007561
Reid Spencera07cb7d2007-02-02 14:41:37 +00007562 // FALL THROUGH.
7563 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007564 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007565 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007566 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007567 m_Specific(Op1)))) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007568 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007569 Op0BO->getOperand(1), Op1,
7570 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007571 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007572 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007573 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007574 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007575 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007576 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007577 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007578 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007579 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007580
Chris Lattner13d4ab42006-05-31 21:14:00 +00007581 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007582 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7583 match(Op0BO->getOperand(0),
7584 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007585 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007586 cast<BinaryOperator>(Op0BO->getOperand(0))
7587 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007588 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007589 Op0BO->getOperand(1), Op1,
7590 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007591 InsertNewInstBefore(YS, I); // (Y << C)
7592 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007593 BinaryOperator::CreateAnd(V1,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007594 ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007595 V1->getName()+".mask");
7596 InsertNewInstBefore(XM, I); // X & (CC << C)
7597
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007598 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007599 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007600
Chris Lattner11021cb2005-09-18 05:12:10 +00007601 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007602 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007603 }
7604
7605
7606 // If the operand is an bitwise operator with a constant RHS, and the
7607 // shift is the only use, we can pull it out of the shift.
7608 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7609 bool isValid = true; // Valid only for And, Or, Xor
7610 bool highBitSet = false; // Transform if high bit of constant set?
7611
7612 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007613 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007614 case Instruction::Add:
7615 isValid = isLeftShift;
7616 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007617 case Instruction::Or:
7618 case Instruction::Xor:
7619 highBitSet = false;
7620 break;
7621 case Instruction::And:
7622 highBitSet = true;
7623 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007624 }
7625
7626 // If this is a signed shift right, and the high bit is modified
7627 // by the logical operation, do not perform the transformation.
7628 // The highBitSet boolean indicates the value of the high bit of
7629 // the constant which would cause it to be modified for this
7630 // operation.
7631 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007632 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007633 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007634
7635 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007636 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007637
7638 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007639 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007640 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007641 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007642
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007643 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007644 NewRHS);
7645 }
7646 }
7647 }
7648 }
7649
Chris Lattnerad0124c2006-01-06 07:52:12 +00007650 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007651 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7652 if (ShiftOp && !ShiftOp->isShift())
7653 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007654
Reid Spencerb83eb642006-10-20 07:07:24 +00007655 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007656 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007657 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7658 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007659 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7660 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7661 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007662
Zhou Sheng4351c642007-04-02 08:20:41 +00007663 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007664
7665 const IntegerType *Ty = cast<IntegerType>(I.getType());
7666
7667 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007668 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007669 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7670 // saturates.
7671 if (AmtSum >= TypeBits) {
7672 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007673 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007674 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7675 }
7676
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007677 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007678 ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007679 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7680 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007681 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007682 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007683
Chris Lattnerb87056f2007-02-05 00:57:54 +00007684 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007685 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007686 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7687 I.getOpcode() == Instruction::LShr) {
7688 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007689 if (AmtSum >= TypeBits)
7690 AmtSum = TypeBits-1;
7691
Chris Lattnerb87056f2007-02-05 00:57:54 +00007692 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007693 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007694 InsertNewInstBefore(Shift, I);
7695
Zhou Shenge9e03f62007-03-28 15:02:20 +00007696 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007697 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007698 }
7699
Chris Lattnerb87056f2007-02-05 00:57:54 +00007700 // Okay, if we get here, one shift must be left, and the other shift must be
7701 // right. See if the amounts are equal.
7702 if (ShiftAmt1 == ShiftAmt2) {
7703 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7704 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007705 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007706 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007707 }
7708 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7709 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007710 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007711 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007712 }
7713 // We can simplify ((X << C) >>s C) into a trunc + sext.
7714 // NOTE: we could do this for any C, but that would make 'unusual' integer
7715 // types. For now, just stick to ones well-supported by the code
7716 // generators.
7717 const Type *SExtType = 0;
7718 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007719 case 1 :
7720 case 8 :
7721 case 16 :
7722 case 32 :
7723 case 64 :
7724 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007725 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007726 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007727 default: break;
7728 }
7729 if (SExtType) {
7730 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7731 InsertNewInstBefore(NewTrunc, I);
7732 return new SExtInst(NewTrunc, Ty);
7733 }
7734 // Otherwise, we can't handle it yet.
7735 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007736 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007737
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007738 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007739 if (I.getOpcode() == Instruction::Shl) {
7740 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7741 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007742 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007743 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007744 InsertNewInstBefore(Shift, I);
7745
Reid Spencer55702aa2007-03-25 21:11:44 +00007746 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007747 return BinaryOperator::CreateAnd(Shift,
7748 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007749 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007750
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007751 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007752 if (I.getOpcode() == Instruction::LShr) {
7753 assert(ShiftOp->getOpcode() == Instruction::Shl);
7754 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007755 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007756 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007757
Reid Spencerd5e30f02007-03-26 17:18:58 +00007758 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007759 return BinaryOperator::CreateAnd(Shift,
7760 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007761 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007762
7763 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7764 } else {
7765 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007766 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007767
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007768 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007769 if (I.getOpcode() == Instruction::Shl) {
7770 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7771 ShiftOp->getOpcode() == Instruction::AShr);
7772 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007773 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007774 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007775 InsertNewInstBefore(Shift, I);
7776
Reid Spencer55702aa2007-03-25 21:11:44 +00007777 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007778 return BinaryOperator::CreateAnd(Shift,
7779 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007780 }
7781
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007782 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007783 if (I.getOpcode() == Instruction::LShr) {
7784 assert(ShiftOp->getOpcode() == Instruction::Shl);
7785 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007786 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007787 InsertNewInstBefore(Shift, I);
7788
Reid Spencer68d27cf2007-03-26 23:45:51 +00007789 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007790 return BinaryOperator::CreateAnd(Shift,
7791 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007792 }
7793
7794 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007795 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007796 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007797 return 0;
7798}
7799
Chris Lattnera1be5662002-05-02 17:06:02 +00007800
Chris Lattnercfd65102005-10-29 04:36:15 +00007801/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7802/// expression. If so, decompose it, returning some value X, such that Val is
7803/// X*Scale+Offset.
7804///
7805static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007806 int &Offset, LLVMContext *Context) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007807 assert(Val->getType() == Type::getInt32Ty(*Context) && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007808 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007809 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007810 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007811 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007812 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7813 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7814 if (I->getOpcode() == Instruction::Shl) {
7815 // This is a value scaled by '1 << the shift amt'.
7816 Scale = 1U << RHS->getZExtValue();
7817 Offset = 0;
7818 return I->getOperand(0);
7819 } else if (I->getOpcode() == Instruction::Mul) {
7820 // This value is scaled by 'RHS'.
7821 Scale = RHS->getZExtValue();
7822 Offset = 0;
7823 return I->getOperand(0);
7824 } else if (I->getOpcode() == Instruction::Add) {
7825 // We have X+C. Check to see if we really have (X*C2)+C1,
7826 // where C1 is divisible by C2.
7827 unsigned SubScale;
7828 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007829 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7830 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007831 Offset += RHS->getZExtValue();
7832 Scale = SubScale;
7833 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007834 }
7835 }
7836 }
7837
7838 // Otherwise, we can't look past this.
7839 Scale = 1;
7840 Offset = 0;
7841 return Val;
7842}
7843
7844
Chris Lattnerb3f83972005-10-24 06:03:58 +00007845/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7846/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007847Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007848 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007849 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007850
Chris Lattnerb53c2382005-10-24 06:22:12 +00007851 // Remove any uses of AI that are dead.
7852 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007853
Chris Lattnerb53c2382005-10-24 06:22:12 +00007854 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7855 Instruction *User = cast<Instruction>(*UI++);
7856 if (isInstructionTriviallyDead(User)) {
7857 while (UI != E && *UI == User)
7858 ++UI; // If this instruction uses AI more than once, don't break UI.
7859
Chris Lattnerb53c2382005-10-24 06:22:12 +00007860 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007861 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007862 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007863 }
7864 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007865
7866 // This requires TargetData to get the alloca alignment and size information.
7867 if (!TD) return 0;
7868
Chris Lattnerb3f83972005-10-24 06:03:58 +00007869 // Get the type really allocated and the type casted to.
7870 const Type *AllocElTy = AI.getAllocatedType();
7871 const Type *CastElTy = PTy->getElementType();
7872 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007873
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007874 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7875 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007876 if (CastElTyAlign < AllocElTyAlign) return 0;
7877
Chris Lattner39387a52005-10-24 06:35:18 +00007878 // If the allocation has multiple uses, only promote it if we are strictly
7879 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007880 // same, we open the door to infinite loops of various kinds. (A reference
7881 // from a dbg.declare doesn't count as a use for this purpose.)
7882 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7883 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007884
Duncan Sands777d2302009-05-09 07:06:46 +00007885 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7886 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007887 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007888
Chris Lattner455fcc82005-10-29 03:19:53 +00007889 // See if we can satisfy the modulus by pulling a scale out of the array
7890 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007891 unsigned ArraySizeScale;
7892 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007893 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007894 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7895 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007896
Chris Lattner455fcc82005-10-29 03:19:53 +00007897 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7898 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007899 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7900 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007901
Chris Lattner455fcc82005-10-29 03:19:53 +00007902 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7903 Value *Amt = 0;
7904 if (Scale == 1) {
7905 Amt = NumElements;
7906 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007907 // If the allocation size is constant, form a constant mul expression
Owen Anderson1d0be152009-08-13 21:58:54 +00007908 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Reid Spencerc5b206b2006-12-31 05:48:39 +00007909 if (isa<ConstantInt>(NumElements))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007910 Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
Dan Gohman6de29f82009-06-15 22:12:54 +00007911 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007912 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007913 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007914 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007915 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007916 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007917 }
7918
Jeff Cohen86796be2007-04-04 16:58:57 +00007919 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007920 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007921 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007922 Amt = InsertNewInstBefore(Tmp, AI);
7923 }
7924
Chris Lattnerb3f83972005-10-24 06:03:58 +00007925 AllocationInst *New;
7926 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +00007927 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007928 else
Owen Anderson50dead02009-07-15 23:53:25 +00007929 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007930 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007931 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007932
Dale Johannesena0a66372009-03-05 00:39:02 +00007933 // If the allocation has one real use plus a dbg.declare, just remove the
7934 // declare.
7935 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7936 EraseInstFromFunction(*DI);
7937 }
7938 // If the allocation has multiple real uses, insert a cast and change all
7939 // things that used it to use the new cast. This will also hack on CI, but it
7940 // will die soon.
7941 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007942 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007943 // New is the allocation instruction, pointer typed. AI is the original
7944 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7945 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007946 InsertNewInstBefore(NewCast, AI);
7947 AI.replaceAllUsesWith(NewCast);
7948 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007949 return ReplaceInstUsesWith(CI, New);
7950}
7951
Chris Lattner70074e02006-05-13 02:06:03 +00007952/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007953/// and return it as type Ty without inserting any new casts and without
7954/// changing the computed value. This is used by code that tries to decide
7955/// whether promoting or shrinking integer operations to wider or smaller types
7956/// will allow us to eliminate a truncate or extend.
7957///
7958/// This is a truncation operation if Ty is smaller than V->getType(), or an
7959/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007960///
7961/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7962/// should return true if trunc(V) can be computed by computing V in the smaller
7963/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7964/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7965/// efficiently truncated.
7966///
7967/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7968/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7969/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007970bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007971 unsigned CastOpc,
7972 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007973 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007974 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007975 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007976
7977 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007978 if (!I) return false;
7979
Dan Gohman6de29f82009-06-15 22:12:54 +00007980 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007981
Chris Lattner951626b2007-08-02 06:11:14 +00007982 // If this is an extension or truncate, we can often eliminate it.
7983 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7984 // If this is a cast from the destination type, we can trivially eliminate
7985 // it, and this will remove a cast overall.
7986 if (I->getOperand(0)->getType() == Ty) {
7987 // If the first operand is itself a cast, and is eliminable, do not count
7988 // this as an eliminable cast. We would prefer to eliminate those two
7989 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007990 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007991 ++NumCastsRemoved;
7992 return true;
7993 }
7994 }
7995
7996 // We can't extend or shrink something that has multiple uses: doing so would
7997 // require duplicating the instruction in general, which isn't profitable.
7998 if (!I->hasOneUse()) return false;
7999
Evan Chengf35fd542009-01-15 17:01:23 +00008000 unsigned Opc = I->getOpcode();
8001 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008002 case Instruction::Add:
8003 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008004 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008005 case Instruction::And:
8006 case Instruction::Or:
8007 case Instruction::Xor:
8008 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00008009 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008010 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00008011 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008012 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008013
Eli Friedman070a9812009-07-13 22:46:01 +00008014 case Instruction::UDiv:
8015 case Instruction::URem: {
8016 // UDiv and URem can be truncated if all the truncated bits are zero.
8017 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8018 uint32_t BitWidth = Ty->getScalarSizeInBits();
8019 if (BitWidth < OrigBitWidth) {
8020 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8021 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8022 MaskedValueIsZero(I->getOperand(1), Mask)) {
8023 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8024 NumCastsRemoved) &&
8025 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8026 NumCastsRemoved);
8027 }
8028 }
8029 break;
8030 }
Chris Lattner46b96052006-11-29 07:18:39 +00008031 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008032 // If we are truncating the result of this SHL, and if it's a shift of a
8033 // constant amount, we can always perform a SHL in a smaller type.
8034 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008035 uint32_t BitWidth = Ty->getScalarSizeInBits();
8036 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00008037 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00008038 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008039 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008040 }
8041 break;
8042 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008043 // If this is a truncate of a logical shr, we can truncate it to a smaller
8044 // lshr iff we know that the bits we would otherwise be shifting in are
8045 // already zeros.
8046 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008047 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8048 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008049 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008050 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008051 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8052 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008053 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008054 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008055 }
8056 }
Chris Lattner46b96052006-11-29 07:18:39 +00008057 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008058 case Instruction::ZExt:
8059 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008060 case Instruction::Trunc:
8061 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008062 // can safely replace it. Note that replacing it does not reduce the number
8063 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008064 if (Opc == CastOpc)
8065 return true;
8066
8067 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008068 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008069 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008070 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008071 case Instruction::Select: {
8072 SelectInst *SI = cast<SelectInst>(I);
8073 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008074 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008075 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008076 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008077 }
Chris Lattner8114b712008-06-18 04:00:49 +00008078 case Instruction::PHI: {
8079 // We can change a phi if we can change all operands.
8080 PHINode *PN = cast<PHINode>(I);
8081 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8082 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008083 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008084 return false;
8085 return true;
8086 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008087 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008088 // TODO: Can handle more cases here.
8089 break;
8090 }
8091
8092 return false;
8093}
8094
8095/// EvaluateInDifferentType - Given an expression that
8096/// CanEvaluateInDifferentType returns true for, actually insert the code to
8097/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008098Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008099 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008100 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00008101 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00008102 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008103
8104 // Otherwise, it must be an instruction.
8105 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008106 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008107 unsigned Opc = I->getOpcode();
8108 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008109 case Instruction::Add:
8110 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008111 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008112 case Instruction::And:
8113 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008114 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008115 case Instruction::AShr:
8116 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008117 case Instruction::Shl:
8118 case Instruction::UDiv:
8119 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008120 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008121 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008122 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008123 break;
8124 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008125 case Instruction::Trunc:
8126 case Instruction::ZExt:
8127 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008128 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008129 // just return the source. There's no need to insert it because it is not
8130 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008131 if (I->getOperand(0)->getType() == Ty)
8132 return I->getOperand(0);
8133
Chris Lattner8114b712008-06-18 04:00:49 +00008134 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008135 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008136 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008137 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008138 case Instruction::Select: {
8139 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8140 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8141 Res = SelectInst::Create(I->getOperand(0), True, False);
8142 break;
8143 }
Chris Lattner8114b712008-06-18 04:00:49 +00008144 case Instruction::PHI: {
8145 PHINode *OPN = cast<PHINode>(I);
8146 PHINode *NPN = PHINode::Create(Ty);
8147 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8148 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8149 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8150 }
8151 Res = NPN;
8152 break;
8153 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008154 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008155 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008156 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008157 break;
8158 }
8159
Chris Lattner8114b712008-06-18 04:00:49 +00008160 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008161 return InsertNewInstBefore(Res, *I);
8162}
8163
Reid Spencer3da59db2006-11-27 01:05:10 +00008164/// @brief Implement the transforms common to all CastInst visitors.
8165Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008166 Value *Src = CI.getOperand(0);
8167
Dan Gohman23d9d272007-05-11 21:10:54 +00008168 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008169 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008170 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008171 if (Instruction::CastOps opc =
8172 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8173 // The first cast (CSrc) is eliminable so we need to fix up or replace
8174 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008175 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008176 }
8177 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008178
Reid Spencer3da59db2006-11-27 01:05:10 +00008179 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008180 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8181 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8182 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008183
8184 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008185 if (isa<PHINode>(Src))
8186 if (Instruction *NV = FoldOpIntoPhi(CI))
8187 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008188
Reid Spencer3da59db2006-11-27 01:05:10 +00008189 return 0;
8190}
8191
Chris Lattner46cd5a12009-01-09 05:44:56 +00008192/// FindElementAtOffset - Given a type and a constant offset, determine whether
8193/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008194/// the specified offset. If so, fill them into NewIndices and return the
8195/// resultant element type, otherwise return null.
8196static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8197 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008198 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008199 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008200 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008201 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008202
8203 // Start with the index over the outer type. Note that the type size
8204 // might be zero (even if the offset isn't zero) if the indexed type
8205 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008206 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008207 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008208 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008209 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008210 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008211
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008212 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008213 if (Offset < 0) {
8214 --FirstIdx;
8215 Offset += TySize;
8216 assert(Offset >= 0);
8217 }
8218 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8219 }
8220
Owen Andersoneed707b2009-07-24 23:12:02 +00008221 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008222
8223 // Index into the types. If we fail, set OrigBase to null.
8224 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008225 // Indexing into tail padding between struct/array elements.
8226 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008227 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008228
Chris Lattner46cd5a12009-01-09 05:44:56 +00008229 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8230 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008231 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8232 "Offset must stay within the indexed type");
8233
Chris Lattner46cd5a12009-01-09 05:44:56 +00008234 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008235 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008236
8237 Offset -= SL->getElementOffset(Elt);
8238 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008239 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008240 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008241 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008242 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008243 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008244 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008245 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008246 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008247 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008248 }
8249 }
8250
Chris Lattner3914f722009-01-24 01:00:13 +00008251 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008252}
8253
Chris Lattnerd3e28342007-04-27 17:44:50 +00008254/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8255Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8256 Value *Src = CI.getOperand(0);
8257
Chris Lattnerd3e28342007-04-27 17:44:50 +00008258 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008259 // If casting the result of a getelementptr instruction with no offset, turn
8260 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008261 if (GEP->hasAllZeroIndices()) {
8262 // Changing the cast operand is usually not a good idea but it is safe
8263 // here because the pointer operand is being replaced with another
8264 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00008265 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008266 CI.setOperand(0, GEP->getOperand(0));
8267 return &CI;
8268 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008269
8270 // If the GEP has a single use, and the base pointer is a bitcast, and the
8271 // GEP computes a constant offset, see if we can convert these three
8272 // instructions into fewer. This typically happens with unions and other
8273 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008274 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008275 if (GEP->hasAllConstantIndices()) {
8276 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008277 ConstantInt *OffsetV =
8278 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008279 int64_t Offset = OffsetV->getSExtValue();
8280
8281 // Get the base pointer input of the bitcast, and the type it points to.
8282 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8283 const Type *GEPIdxTy =
8284 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008285 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008286 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008287 // If we were able to index down into an element, create the GEP
8288 // and bitcast the result. This eliminates one bitcast, potentially
8289 // two.
8290 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8291 NewIndices.begin(),
8292 NewIndices.end(), "");
8293 InsertNewInstBefore(NGEP, CI);
8294 NGEP->takeName(GEP);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008295 if (cast<GEPOperator>(GEP)->isInBounds())
8296 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner9bc14642007-04-28 00:57:34 +00008297
Chris Lattner46cd5a12009-01-09 05:44:56 +00008298 if (isa<BitCastInst>(CI))
8299 return new BitCastInst(NGEP, CI.getType());
8300 assert(isa<PtrToIntInst>(CI));
8301 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008302 }
8303 }
8304 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008305 }
8306
8307 return commonCastTransforms(CI);
8308}
8309
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008310/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8311/// type like i42. We don't want to introduce operations on random non-legal
8312/// integer types where they don't already exist in the code. In the future,
8313/// we should consider making this based off target-data, so that 32-bit targets
8314/// won't get i64 operations etc.
8315static bool isSafeIntegerType(const Type *Ty) {
8316 switch (Ty->getPrimitiveSizeInBits()) {
8317 case 8:
8318 case 16:
8319 case 32:
8320 case 64:
8321 return true;
8322 default:
8323 return false;
8324 }
8325}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008326
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008327/// commonIntCastTransforms - This function implements the common transforms
8328/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008329Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8330 if (Instruction *Result = commonCastTransforms(CI))
8331 return Result;
8332
8333 Value *Src = CI.getOperand(0);
8334 const Type *SrcTy = Src->getType();
8335 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008336 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8337 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008338
Reid Spencer3da59db2006-11-27 01:05:10 +00008339 // See if we can simplify any instructions used by the LHS whose sole
8340 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008341 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008342 return &CI;
8343
8344 // If the source isn't an instruction or has more than one use then we
8345 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008346 Instruction *SrcI = dyn_cast<Instruction>(Src);
8347 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008348 return 0;
8349
Chris Lattnerc739cd62007-03-03 05:27:34 +00008350 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008351 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008352 // Only do this if the dest type is a simple type, don't convert the
8353 // expression tree to something weird like i93 unless the source is also
8354 // strange.
8355 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008356 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8357 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008358 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008359 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008360 // eliminates the cast, so it is always a win. If this is a zero-extension,
8361 // we need to do an AND to maintain the clear top-part of the computation,
8362 // so we require that the input have eliminated at least one cast. If this
8363 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008364 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008365 bool DoXForm = false;
8366 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008367 switch (CI.getOpcode()) {
8368 default:
8369 // All the others use floating point so we shouldn't actually
8370 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008371 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008372 case Instruction::Trunc:
8373 DoXForm = true;
8374 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008375 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008376 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008377 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008378 // If it's unnecessary to issue an AND to clear the high bits, it's
8379 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008380 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008381 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8382 if (MaskedValueIsZero(TryRes, Mask))
8383 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008384
8385 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008386 if (TryI->use_empty())
8387 EraseInstFromFunction(*TryI);
8388 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008389 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008390 }
Evan Chengf35fd542009-01-15 17:01:23 +00008391 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008392 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008393 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008394 // If we do not have to emit the truncate + sext pair, then it's always
8395 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008396 //
8397 // It's not safe to eliminate the trunc + sext pair if one of the
8398 // eliminated cast is a truncate. e.g.
8399 // t2 = trunc i32 t1 to i16
8400 // t3 = sext i16 t2 to i32
8401 // !=
8402 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008403 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008404 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8405 if (NumSignBits > (DestBitSize - SrcBitSize))
8406 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008407
8408 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008409 if (TryI->use_empty())
8410 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008411 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008412 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008413 }
Evan Chengf35fd542009-01-15 17:01:23 +00008414 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008415
8416 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008417 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8418 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008419 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8420 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008421 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008422 // Just replace this cast with the result.
8423 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008424
Reid Spencer3da59db2006-11-27 01:05:10 +00008425 assert(Res->getType() == DestTy);
8426 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008427 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008428 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008429 // Just replace this cast with the result.
8430 return ReplaceInstUsesWith(CI, Res);
8431 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008432 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008433
8434 // If the high bits are already zero, just replace this cast with the
8435 // result.
8436 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8437 if (MaskedValueIsZero(Res, Mask))
8438 return ReplaceInstUsesWith(CI, Res);
8439
8440 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008441 Constant *C = ConstantInt::get(*Context,
8442 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008443 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008444 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008445 case Instruction::SExt: {
8446 // If the high bits are already filled with sign bit, just replace this
8447 // cast with the result.
8448 unsigned NumSignBits = ComputeNumSignBits(Res);
8449 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008450 return ReplaceInstUsesWith(CI, Res);
8451
Reid Spencer3da59db2006-11-27 01:05:10 +00008452 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008453 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008454 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8455 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008456 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008457 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008458 }
8459 }
8460
8461 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8462 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8463
8464 switch (SrcI->getOpcode()) {
8465 case Instruction::Add:
8466 case Instruction::Mul:
8467 case Instruction::And:
8468 case Instruction::Or:
8469 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008470 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008471 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8472 // Don't insert two casts unless at least one can be eliminated.
8473 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008474 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman65445c52009-07-13 21:45:57 +00008475 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8476 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008477 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008478 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008479 }
8480 }
8481
8482 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8483 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8484 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008485 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008486 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008487 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008488 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008489 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008490 }
8491 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008492
Eli Friedman65445c52009-07-13 21:45:57 +00008493 case Instruction::Shl: {
8494 // Canonicalize trunc inside shl, if we can.
8495 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8496 if (CI && DestBitSize < SrcBitSize &&
8497 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8498 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8499 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008500 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008501 }
8502 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008503 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008504 }
8505 return 0;
8506}
8507
Chris Lattner8a9f5712007-04-11 06:57:46 +00008508Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008509 if (Instruction *Result = commonIntCastTransforms(CI))
8510 return Result;
8511
8512 Value *Src = CI.getOperand(0);
8513 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008514 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8515 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008516
8517 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008518 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008519 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008520 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersona7235ea2009-07-31 20:28:14 +00008521 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008522 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008523 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008524
Chris Lattner4f9797d2009-03-24 18:15:30 +00008525 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8526 ConstantInt *ShAmtV = 0;
8527 Value *ShiftOp = 0;
8528 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008529 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008530 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8531
8532 // Get a mask for the bits shifting in.
8533 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8534 if (MaskedValueIsZero(ShiftOp, Mask)) {
8535 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008536 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008537
8538 // Okay, we can shrink this. Truncate the input, then return a new
8539 // shift.
8540 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008541 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008542 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008543 }
8544 }
8545
8546 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008547}
8548
Evan Chengb98a10e2008-03-24 00:21:34 +00008549/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8550/// in order to eliminate the icmp.
8551Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8552 bool DoXform) {
8553 // If we are just checking for a icmp eq of a single bit and zext'ing it
8554 // to an integer, then shift the bit to the appropriate place and then
8555 // cast to integer to avoid the comparison.
8556 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8557 const APInt &Op1CV = Op1C->getValue();
8558
8559 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8560 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8561 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8562 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8563 if (!DoXform) return ICI;
8564
8565 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008566 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008567 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008568 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008569 In->getName()+".lobit"),
8570 CI);
8571 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008572 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008573 false/*ZExt*/, "tmp", &CI);
8574
8575 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008576 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008577 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008578 In->getName()+".not"),
8579 CI);
8580 }
8581
8582 return ReplaceInstUsesWith(CI, In);
8583 }
8584
8585
8586
8587 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8588 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8589 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8590 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8591 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8592 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8593 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8594 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8595 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8596 // This only works for EQ and NE
8597 ICI->isEquality()) {
8598 // If Op1C some other power of two, convert:
8599 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8600 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8601 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8602 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8603
8604 APInt KnownZeroMask(~KnownZero);
8605 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8606 if (!DoXform) return ICI;
8607
8608 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8609 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8610 // (X&4) == 2 --> false
8611 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008612 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008613 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008614 return ReplaceInstUsesWith(CI, Res);
8615 }
8616
8617 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8618 Value *In = ICI->getOperand(0);
8619 if (ShiftAmt) {
8620 // Perform a logical shr by shiftamt.
8621 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008622 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersoneed707b2009-07-24 23:12:02 +00008623 ConstantInt::get(In->getType(), ShiftAmt),
Evan Chengb98a10e2008-03-24 00:21:34 +00008624 In->getName()+".lobit"), CI);
8625 }
8626
8627 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008628 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008629 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008630 InsertNewInstBefore(cast<Instruction>(In), CI);
8631 }
8632
8633 if (CI.getType() == In->getType())
8634 return ReplaceInstUsesWith(CI, In);
8635 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008636 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008637 }
8638 }
8639 }
8640
8641 return 0;
8642}
8643
Chris Lattner8a9f5712007-04-11 06:57:46 +00008644Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008645 // If one of the common conversion will work ..
8646 if (Instruction *Result = commonIntCastTransforms(CI))
8647 return Result;
8648
8649 Value *Src = CI.getOperand(0);
8650
Chris Lattnera84f47c2009-02-17 20:47:23 +00008651 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8652 // types and if the sizes are just right we can convert this into a logical
8653 // 'and' which will be much cheaper than the pair of casts.
8654 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8655 // Get the sizes of the types involved. We know that the intermediate type
8656 // will be smaller than A or C, but don't know the relation between A and C.
8657 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008658 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8659 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8660 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008661 // If we're actually extending zero bits, then if
8662 // SrcSize < DstSize: zext(a & mask)
8663 // SrcSize == DstSize: a & mask
8664 // SrcSize > DstSize: trunc(a) & mask
8665 if (SrcSize < DstSize) {
8666 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008667 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008668 Instruction *And =
8669 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8670 InsertNewInstBefore(And, CI);
8671 return new ZExtInst(And, CI.getType());
8672 } else if (SrcSize == DstSize) {
8673 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008674 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008675 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008676 } else if (SrcSize > DstSize) {
8677 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8678 InsertNewInstBefore(Trunc, CI);
8679 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008680 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008681 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008682 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008683 }
8684 }
8685
Evan Chengb98a10e2008-03-24 00:21:34 +00008686 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8687 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008688
Evan Chengb98a10e2008-03-24 00:21:34 +00008689 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8690 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8691 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8692 // of the (zext icmp) will be transformed.
8693 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8694 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8695 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8696 (transformZExtICmp(LHS, CI, false) ||
8697 transformZExtICmp(RHS, CI, false))) {
8698 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8699 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008700 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008701 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008702 }
8703
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008704 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008705 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8706 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8707 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8708 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008709 if (TI0->getType() == CI.getType())
8710 return
8711 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008712 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008713 }
8714
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008715 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8716 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8717 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8718 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8719 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8720 And->getOperand(1) == C)
8721 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8722 Value *TI0 = TI->getOperand(0);
8723 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008724 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008725 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8726 InsertNewInstBefore(NewAnd, *And);
8727 return BinaryOperator::CreateXor(NewAnd, ZC);
8728 }
8729 }
8730
Reid Spencer3da59db2006-11-27 01:05:10 +00008731 return 0;
8732}
8733
Chris Lattner8a9f5712007-04-11 06:57:46 +00008734Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008735 if (Instruction *I = commonIntCastTransforms(CI))
8736 return I;
8737
Chris Lattner8a9f5712007-04-11 06:57:46 +00008738 Value *Src = CI.getOperand(0);
8739
Dan Gohman1975d032008-10-30 20:40:10 +00008740 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008741 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008742 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008743 Constant::getAllOnesValue(CI.getType()),
8744 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008745
8746 // See if the value being truncated is already sign extended. If so, just
8747 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008748 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008749 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008750 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8751 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8752 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008753 unsigned NumSignBits = ComputeNumSignBits(Op);
8754
8755 if (OpBits == DestBits) {
8756 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8757 // bits, it is already ready.
8758 if (NumSignBits > DestBits-MidBits)
8759 return ReplaceInstUsesWith(CI, Op);
8760 } else if (OpBits < DestBits) {
8761 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8762 // bits, just sext from i32.
8763 if (NumSignBits > OpBits-MidBits)
8764 return new SExtInst(Op, CI.getType(), "tmp");
8765 } else {
8766 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8767 // bits, just truncate to i32.
8768 if (NumSignBits > OpBits-MidBits)
8769 return new TruncInst(Op, CI.getType(), "tmp");
8770 }
8771 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008772
8773 // If the input is a shl/ashr pair of a same constant, then this is a sign
8774 // extension from a smaller value. If we could trust arbitrary bitwidth
8775 // integers, we could turn this into a truncate to the smaller bit and then
8776 // use a sext for the whole extension. Since we don't, look deeper and check
8777 // for a truncate. If the source and dest are the same type, eliminate the
8778 // trunc and extend and just do shifts. For example, turn:
8779 // %a = trunc i32 %i to i8
8780 // %b = shl i8 %a, 6
8781 // %c = ashr i8 %b, 6
8782 // %d = sext i8 %c to i32
8783 // into:
8784 // %a = shl i32 %i, 30
8785 // %d = ashr i32 %a, 30
8786 Value *A = 0;
8787 ConstantInt *BA = 0, *CA = 0;
8788 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008789 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008790 BA == CA && isa<TruncInst>(A)) {
8791 Value *I = cast<TruncInst>(A)->getOperand(0);
8792 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008793 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8794 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008795 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008796 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattner46bbad22008-08-06 07:35:52 +00008797 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8798 CI.getName()), CI);
8799 return BinaryOperator::CreateAShr(I, ShAmtV);
8800 }
8801 }
8802
Chris Lattnerba417832007-04-11 06:12:58 +00008803 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008804}
8805
Chris Lattnerb7530652008-01-27 05:29:54 +00008806/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8807/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008808static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008809 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008810 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008811 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008812 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8813 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008814 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008815 return 0;
8816}
8817
8818/// LookThroughFPExtensions - If this is an fp extension instruction, look
8819/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008820static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008821 if (Instruction *I = dyn_cast<Instruction>(V))
8822 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008823 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008824
8825 // If this value is a constant, return the constant in the smallest FP type
8826 // that can accurately represent it. This allows us to turn
8827 // (float)((double)X+2.0) into x+2.0f.
8828 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008829 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008830 return V; // No constant folding of this.
8831 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008832 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008833 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008834 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008835 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008836 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008837 return V;
8838 // Don't try to shrink to various long double types.
8839 }
8840
8841 return V;
8842}
8843
8844Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8845 if (Instruction *I = commonCastTransforms(CI))
8846 return I;
8847
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008848 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008849 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008850 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008851 // many builtins (sqrt, etc).
8852 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8853 if (OpI && OpI->hasOneUse()) {
8854 switch (OpI->getOpcode()) {
8855 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008856 case Instruction::FAdd:
8857 case Instruction::FSub:
8858 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008859 case Instruction::FDiv:
8860 case Instruction::FRem:
8861 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008862 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8863 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008864 if (LHSTrunc->getType() != SrcTy &&
8865 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008866 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008867 // If the source types were both smaller than the destination type of
8868 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008869 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8870 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008871 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8872 CI.getType(), CI);
8873 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8874 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008875 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008876 }
8877 }
8878 break;
8879 }
8880 }
8881 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008882}
8883
8884Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8885 return commonCastTransforms(CI);
8886}
8887
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008888Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008889 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8890 if (OpI == 0)
8891 return commonCastTransforms(FI);
8892
8893 // fptoui(uitofp(X)) --> X
8894 // fptoui(sitofp(X)) --> X
8895 // This is safe if the intermediate type has enough bits in its mantissa to
8896 // accurately represent all values of X. For example, do not do this with
8897 // i64->float->i64. This is also safe for sitofp case, because any negative
8898 // 'X' value would cause an undefined result for the fptoui.
8899 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8900 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008901 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008902 OpI->getType()->getFPMantissaWidth())
8903 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008904
8905 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008906}
8907
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008908Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008909 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8910 if (OpI == 0)
8911 return commonCastTransforms(FI);
8912
8913 // fptosi(sitofp(X)) --> X
8914 // fptosi(uitofp(X)) --> X
8915 // This is safe if the intermediate type has enough bits in its mantissa to
8916 // accurately represent all values of X. For example, do not do this with
8917 // i64->float->i64. This is also safe for sitofp case, because any negative
8918 // 'X' value would cause an undefined result for the fptoui.
8919 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8920 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008921 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008922 OpI->getType()->getFPMantissaWidth())
8923 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008924
8925 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008926}
8927
8928Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8929 return commonCastTransforms(CI);
8930}
8931
8932Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8933 return commonCastTransforms(CI);
8934}
8935
Chris Lattnera0e69692009-03-24 18:35:40 +00008936Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8937 // If the destination integer type is smaller than the intptr_t type for
8938 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8939 // trunc to be exposed to other transforms. Don't do this for extending
8940 // ptrtoint's, because we don't know if the target sign or zero extends its
8941 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008942 if (TD &&
8943 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008944 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
Owen Anderson1d0be152009-08-13 21:58:54 +00008945 TD->getIntPtrType(CI.getContext()),
Chris Lattnera0e69692009-03-24 18:35:40 +00008946 "tmp"), CI);
8947 return new TruncInst(P, CI.getType());
8948 }
8949
Chris Lattnerd3e28342007-04-27 17:44:50 +00008950 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008951}
8952
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008953Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008954 // If the source integer type is larger than the intptr_t type for
8955 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8956 // allows the trunc to be exposed to other transforms. Don't do this for
8957 // extending inttoptr's, because we don't know if the target sign or zero
8958 // extends to pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008959 if (TD &&
8960 CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008961 TD->getPointerSizeInBits()) {
8962 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
Owen Anderson1d0be152009-08-13 21:58:54 +00008963 TD->getIntPtrType(CI.getContext()),
Chris Lattnera0e69692009-03-24 18:35:40 +00008964 "tmp"), CI);
8965 return new IntToPtrInst(P, CI.getType());
8966 }
8967
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008968 if (Instruction *I = commonCastTransforms(CI))
8969 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008970
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008971 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008972}
8973
Chris Lattnerd3e28342007-04-27 17:44:50 +00008974Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008975 // If the operands are integer typed then apply the integer transforms,
8976 // otherwise just apply the common ones.
8977 Value *Src = CI.getOperand(0);
8978 const Type *SrcTy = Src->getType();
8979 const Type *DestTy = CI.getType();
8980
Eli Friedman7e25d452009-07-13 20:53:00 +00008981 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008982 if (Instruction *I = commonPointerCastTransforms(CI))
8983 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008984 } else {
8985 if (Instruction *Result = commonCastTransforms(CI))
8986 return Result;
8987 }
8988
8989
8990 // Get rid of casts from one type to the same type. These are useless and can
8991 // be replaced by the operand.
8992 if (DestTy == Src->getType())
8993 return ReplaceInstUsesWith(CI, Src);
8994
Reid Spencer3da59db2006-11-27 01:05:10 +00008995 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008996 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8997 const Type *DstElTy = DstPTy->getElementType();
8998 const Type *SrcElTy = SrcPTy->getElementType();
8999
Nate Begeman83ad90a2008-03-31 00:22:16 +00009000 // If the address spaces don't match, don't eliminate the bitcast, which is
9001 // required for changing types.
9002 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9003 return 0;
9004
Chris Lattnerd3e28342007-04-27 17:44:50 +00009005 // If we are casting a malloc or alloca to a pointer to a type of the same
9006 // size, rewrite the allocation instruction to allocate the "right" type.
9007 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9008 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9009 return V;
9010
Chris Lattnerd717c182007-05-05 22:32:24 +00009011 // If the source and destination are pointers, and this cast is equivalent
9012 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00009013 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00009014 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00009015 unsigned NumZeros = 0;
9016 while (SrcElTy != DstElTy &&
9017 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9018 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9019 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9020 ++NumZeros;
9021 }
Chris Lattner4e998b22004-09-29 05:07:12 +00009022
Chris Lattnerd3e28342007-04-27 17:44:50 +00009023 // If we found a path from the src to dest, create the getelementptr now.
9024 if (SrcElTy == DstElTy) {
9025 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00009026 Instruction *GEP = GetElementPtrInst::Create(Src,
9027 Idxs.begin(), Idxs.end(), "",
9028 ((Instruction*) NULL));
9029 cast<GEPOperator>(GEP)->setIsInBounds(true);
9030 return GEP;
Chris Lattner9fb92132006-04-12 18:09:35 +00009031 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009032 }
Chris Lattner24c8e382003-07-24 17:35:25 +00009033
Eli Friedman2451a642009-07-18 23:06:53 +00009034 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9035 if (DestVTy->getNumElements() == 1) {
9036 if (!isa<VectorType>(SrcTy)) {
9037 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
9038 DestVTy->getElementType(), CI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009039 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Owen Anderson1d0be152009-08-13 21:58:54 +00009040 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009041 }
9042 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9043 }
9044 }
9045
9046 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9047 if (SrcVTy->getNumElements() == 1) {
9048 if (!isa<VectorType>(DestTy)) {
9049 Instruction *Elem =
Owen Anderson1d0be152009-08-13 21:58:54 +00009050 ExtractElementInst::Create(Src, Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009051 InsertNewInstBefore(Elem, CI);
9052 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9053 }
9054 }
9055 }
9056
Reid Spencer3da59db2006-11-27 01:05:10 +00009057 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9058 if (SVI->hasOneUse()) {
9059 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9060 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009061 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009062 cast<VectorType>(DestTy)->getNumElements() ==
9063 SVI->getType()->getNumElements() &&
9064 SVI->getType()->getNumElements() ==
9065 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009066 CastInst *Tmp;
9067 // If either of the operands is a cast from CI.getType(), then
9068 // evaluating the shuffle in the casted destination's type will allow
9069 // us to eliminate at least one cast.
9070 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9071 Tmp->getOperand(0)->getType() == DestTy) ||
9072 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9073 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009074 Value *LHS = InsertCastBefore(Instruction::BitCast,
9075 SVI->getOperand(0), DestTy, CI);
9076 Value *RHS = InsertCastBefore(Instruction::BitCast,
9077 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009078 // Return a new shuffle vector. Use the same element ID's, as we
9079 // know the vector types match #elts.
9080 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009081 }
9082 }
9083 }
9084 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009085 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009086}
9087
Chris Lattnere576b912004-04-09 23:46:01 +00009088/// GetSelectFoldableOperands - We want to turn code that looks like this:
9089/// %C = or %A, %B
9090/// %D = select %cond, %C, %A
9091/// into:
9092/// %C = select %cond, %B, 0
9093/// %D = or %A, %C
9094///
9095/// Assuming that the specified instruction is an operand to the select, return
9096/// a bitmask indicating which operands of this instruction are foldable if they
9097/// equal the other incoming value of the select.
9098///
9099static unsigned GetSelectFoldableOperands(Instruction *I) {
9100 switch (I->getOpcode()) {
9101 case Instruction::Add:
9102 case Instruction::Mul:
9103 case Instruction::And:
9104 case Instruction::Or:
9105 case Instruction::Xor:
9106 return 3; // Can fold through either operand.
9107 case Instruction::Sub: // Can only fold on the amount subtracted.
9108 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009109 case Instruction::LShr:
9110 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009111 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009112 default:
9113 return 0; // Cannot fold
9114 }
9115}
9116
9117/// GetSelectFoldableConstant - For the same transformation as the previous
9118/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009119static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009120 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009121 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009122 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009123 case Instruction::Add:
9124 case Instruction::Sub:
9125 case Instruction::Or:
9126 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009127 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009128 case Instruction::LShr:
9129 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009130 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009131 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009132 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009133 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009134 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009135 }
9136}
9137
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009138/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9139/// have the same opcode and only one use each. Try to simplify this.
9140Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9141 Instruction *FI) {
9142 if (TI->getNumOperands() == 1) {
9143 // If this is a non-volatile load or a cast from the same type,
9144 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009145 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009146 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9147 return 0;
9148 } else {
9149 return 0; // unknown unary op.
9150 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009151
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009152 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009153 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009154 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009155 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009156 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009157 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009158 }
9159
Reid Spencer832254e2007-02-02 02:16:23 +00009160 // Only handle binary operators here.
9161 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009162 return 0;
9163
9164 // Figure out if the operations have any operands in common.
9165 Value *MatchOp, *OtherOpT, *OtherOpF;
9166 bool MatchIsOpZero;
9167 if (TI->getOperand(0) == FI->getOperand(0)) {
9168 MatchOp = TI->getOperand(0);
9169 OtherOpT = TI->getOperand(1);
9170 OtherOpF = FI->getOperand(1);
9171 MatchIsOpZero = true;
9172 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9173 MatchOp = TI->getOperand(1);
9174 OtherOpT = TI->getOperand(0);
9175 OtherOpF = FI->getOperand(0);
9176 MatchIsOpZero = false;
9177 } else if (!TI->isCommutative()) {
9178 return 0;
9179 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9180 MatchOp = TI->getOperand(0);
9181 OtherOpT = TI->getOperand(1);
9182 OtherOpF = FI->getOperand(0);
9183 MatchIsOpZero = true;
9184 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9185 MatchOp = TI->getOperand(1);
9186 OtherOpT = TI->getOperand(0);
9187 OtherOpF = FI->getOperand(1);
9188 MatchIsOpZero = true;
9189 } else {
9190 return 0;
9191 }
9192
9193 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009194 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9195 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009196 InsertNewInstBefore(NewSI, SI);
9197
9198 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9199 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009200 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009201 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009202 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009203 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009204 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009205 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009206}
9207
Evan Chengde621922009-03-31 20:42:45 +00009208static bool isSelect01(Constant *C1, Constant *C2) {
9209 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9210 if (!C1I)
9211 return false;
9212 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9213 if (!C2I)
9214 return false;
9215 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9216}
9217
9218/// FoldSelectIntoOp - Try fold the select into one of the operands to
9219/// facilitate further optimization.
9220Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9221 Value *FalseVal) {
9222 // See the comment above GetSelectFoldableOperands for a description of the
9223 // transformation we are doing here.
9224 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9225 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9226 !isa<Constant>(FalseVal)) {
9227 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9228 unsigned OpToFold = 0;
9229 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9230 OpToFold = 1;
9231 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9232 OpToFold = 2;
9233 }
9234
9235 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009236 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009237 Value *OOp = TVI->getOperand(2-OpToFold);
9238 // Avoid creating select between 2 constants unless it's selecting
9239 // between 0 and 1.
9240 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9241 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9242 InsertNewInstBefore(NewSel, SI);
9243 NewSel->takeName(TVI);
9244 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9245 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009246 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009247 }
9248 }
9249 }
9250 }
9251 }
9252
9253 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9254 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9255 !isa<Constant>(TrueVal)) {
9256 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9257 unsigned OpToFold = 0;
9258 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9259 OpToFold = 1;
9260 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9261 OpToFold = 2;
9262 }
9263
9264 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009265 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009266 Value *OOp = FVI->getOperand(2-OpToFold);
9267 // Avoid creating select between 2 constants unless it's selecting
9268 // between 0 and 1.
9269 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9270 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9271 InsertNewInstBefore(NewSel, SI);
9272 NewSel->takeName(FVI);
9273 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9274 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009275 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009276 }
9277 }
9278 }
9279 }
9280 }
9281
9282 return 0;
9283}
9284
Dan Gohman81b28ce2008-09-16 18:46:06 +00009285/// visitSelectInstWithICmp - Visit a SelectInst that has an
9286/// ICmpInst as its first operand.
9287///
9288Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9289 ICmpInst *ICI) {
9290 bool Changed = false;
9291 ICmpInst::Predicate Pred = ICI->getPredicate();
9292 Value *CmpLHS = ICI->getOperand(0);
9293 Value *CmpRHS = ICI->getOperand(1);
9294 Value *TrueVal = SI.getTrueValue();
9295 Value *FalseVal = SI.getFalseValue();
9296
9297 // Check cases where the comparison is with a constant that
9298 // can be adjusted to fit the min/max idiom. We may edit ICI in
9299 // place here, so make sure the select is the only user.
9300 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009301 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009302 switch (Pred) {
9303 default: break;
9304 case ICmpInst::ICMP_ULT:
9305 case ICmpInst::ICMP_SLT: {
9306 // X < MIN ? T : F --> F
9307 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9308 return ReplaceInstUsesWith(SI, FalseVal);
9309 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009310 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009311 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9312 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9313 Pred = ICmpInst::getSwappedPredicate(Pred);
9314 CmpRHS = AdjustedRHS;
9315 std::swap(FalseVal, TrueVal);
9316 ICI->setPredicate(Pred);
9317 ICI->setOperand(1, CmpRHS);
9318 SI.setOperand(1, TrueVal);
9319 SI.setOperand(2, FalseVal);
9320 Changed = true;
9321 }
9322 break;
9323 }
9324 case ICmpInst::ICMP_UGT:
9325 case ICmpInst::ICMP_SGT: {
9326 // X > MAX ? T : F --> F
9327 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9328 return ReplaceInstUsesWith(SI, FalseVal);
9329 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009330 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009331 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9332 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9333 Pred = ICmpInst::getSwappedPredicate(Pred);
9334 CmpRHS = AdjustedRHS;
9335 std::swap(FalseVal, TrueVal);
9336 ICI->setPredicate(Pred);
9337 ICI->setOperand(1, CmpRHS);
9338 SI.setOperand(1, TrueVal);
9339 SI.setOperand(2, FalseVal);
9340 Changed = true;
9341 }
9342 break;
9343 }
9344 }
9345
Dan Gohman1975d032008-10-30 20:40:10 +00009346 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9347 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009348 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009349 if (match(TrueVal, m_ConstantInt<-1>()) &&
9350 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009351 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009352 else if (match(TrueVal, m_ConstantInt<0>()) &&
9353 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009354 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9355
Dan Gohman1975d032008-10-30 20:40:10 +00009356 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9357 // If we are just checking for a icmp eq of a single bit and zext'ing it
9358 // to an integer, then shift the bit to the appropriate place and then
9359 // cast to integer to avoid the comparison.
9360 const APInt &Op1CV = CI->getValue();
9361
9362 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9363 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9364 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009365 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009366 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009367 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009368 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009369 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009370 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009371 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009372 if (In->getType() != SI.getType())
9373 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009374 true/*SExt*/, "tmp", ICI);
9375
9376 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009377 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009378 In->getName()+".not"), *ICI);
9379
9380 return ReplaceInstUsesWith(SI, In);
9381 }
9382 }
9383 }
9384
Dan Gohman81b28ce2008-09-16 18:46:06 +00009385 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9386 // Transform (X == Y) ? X : Y -> Y
9387 if (Pred == ICmpInst::ICMP_EQ)
9388 return ReplaceInstUsesWith(SI, FalseVal);
9389 // Transform (X != Y) ? X : Y -> X
9390 if (Pred == ICmpInst::ICMP_NE)
9391 return ReplaceInstUsesWith(SI, TrueVal);
9392 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9393
9394 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9395 // Transform (X == Y) ? Y : X -> X
9396 if (Pred == ICmpInst::ICMP_EQ)
9397 return ReplaceInstUsesWith(SI, FalseVal);
9398 // Transform (X != Y) ? Y : X -> Y
9399 if (Pred == ICmpInst::ICMP_NE)
9400 return ReplaceInstUsesWith(SI, TrueVal);
9401 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9402 }
9403
9404 /// NOTE: if we wanted to, this is where to detect integer ABS
9405
9406 return Changed ? &SI : 0;
9407}
9408
Chris Lattner3d69f462004-03-12 05:52:32 +00009409Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009410 Value *CondVal = SI.getCondition();
9411 Value *TrueVal = SI.getTrueValue();
9412 Value *FalseVal = SI.getFalseValue();
9413
9414 // select true, X, Y -> X
9415 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009416 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009417 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009418
9419 // select C, X, X -> X
9420 if (TrueVal == FalseVal)
9421 return ReplaceInstUsesWith(SI, TrueVal);
9422
Chris Lattnere87597f2004-10-16 18:11:37 +00009423 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9424 return ReplaceInstUsesWith(SI, FalseVal);
9425 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9426 return ReplaceInstUsesWith(SI, TrueVal);
9427 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9428 if (isa<Constant>(TrueVal))
9429 return ReplaceInstUsesWith(SI, TrueVal);
9430 else
9431 return ReplaceInstUsesWith(SI, FalseVal);
9432 }
9433
Owen Anderson1d0be152009-08-13 21:58:54 +00009434 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009435 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009436 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009437 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009438 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009439 } else {
9440 // Change: A = select B, false, C --> A = and !B, C
9441 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009442 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009443 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009444 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009445 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009446 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009447 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009448 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009449 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009450 } else {
9451 // Change: A = select B, C, true --> A = or !B, C
9452 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009453 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009454 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009455 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009456 }
9457 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009458
9459 // select a, b, a -> a&b
9460 // select a, a, b -> a|b
9461 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009462 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009463 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009464 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009465 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009466
Chris Lattner2eefe512004-04-09 19:05:30 +00009467 // Selecting between two integer constants?
9468 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9469 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009470 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009471 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009472 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009473 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009474 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009475 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009476 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009477 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009478 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009479 }
Chris Lattner457dd822004-06-09 07:59:58 +00009480
Reid Spencere4d87aa2006-12-23 06:05:41 +00009481 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009482 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009483 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009484 // non-constant value, eliminate this whole mess. This corresponds to
9485 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009486 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009487 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009488 cast<Constant>(IC->getOperand(1))->isNullValue())
9489 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9490 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009491 isa<ConstantInt>(ICA->getOperand(1)) &&
9492 (ICA->getOperand(1) == TrueValC ||
9493 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009494 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9495 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009496 // know whether we have a icmp_ne or icmp_eq and whether the
9497 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009498 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009499 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009500 Value *V = ICA;
9501 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009502 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009503 Instruction::Xor, V, ICA->getOperand(1)), SI);
9504 return ReplaceInstUsesWith(SI, V);
9505 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009506 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009507 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009508
9509 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009510 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9511 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009512 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009513 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9514 // This is not safe in general for floating point:
9515 // consider X== -0, Y== +0.
9516 // It becomes safe if either operand is a nonzero constant.
9517 ConstantFP *CFPt, *CFPf;
9518 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9519 !CFPt->getValueAPF().isZero()) ||
9520 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9521 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009522 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009523 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009524 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009525 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009526 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009527 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009528
Reid Spencere4d87aa2006-12-23 06:05:41 +00009529 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009530 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009531 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9532 // This is not safe in general for floating point:
9533 // consider X== -0, Y== +0.
9534 // It becomes safe if either operand is a nonzero constant.
9535 ConstantFP *CFPt, *CFPf;
9536 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9537 !CFPt->getValueAPF().isZero()) ||
9538 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9539 !CFPf->getValueAPF().isZero()))
9540 return ReplaceInstUsesWith(SI, FalseVal);
9541 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009542 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009543 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9544 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009545 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009546 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009547 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009548 }
9549
9550 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009551 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9552 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9553 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009554
Chris Lattner87875da2005-01-13 22:52:24 +00009555 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9556 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9557 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009558 Instruction *AddOp = 0, *SubOp = 0;
9559
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009560 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9561 if (TI->getOpcode() == FI->getOpcode())
9562 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9563 return IV;
9564
9565 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9566 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009567 if ((TI->getOpcode() == Instruction::Sub &&
9568 FI->getOpcode() == Instruction::Add) ||
9569 (TI->getOpcode() == Instruction::FSub &&
9570 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009571 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009572 } else if ((FI->getOpcode() == Instruction::Sub &&
9573 TI->getOpcode() == Instruction::Add) ||
9574 (FI->getOpcode() == Instruction::FSub &&
9575 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009576 AddOp = TI; SubOp = FI;
9577 }
9578
9579 if (AddOp) {
9580 Value *OtherAddOp = 0;
9581 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9582 OtherAddOp = AddOp->getOperand(1);
9583 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9584 OtherAddOp = AddOp->getOperand(0);
9585 }
9586
9587 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009588 // So at this point we know we have (Y -> OtherAddOp):
9589 // select C, (add X, Y), (sub X, Z)
9590 Value *NegVal; // Compute -Z
9591 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009592 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009593 } else {
9594 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009595 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009596 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009597 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009598
9599 Value *NewTrueOp = OtherAddOp;
9600 Value *NewFalseOp = NegVal;
9601 if (AddOp != TI)
9602 std::swap(NewTrueOp, NewFalseOp);
9603 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009604 SelectInst::Create(CondVal, NewTrueOp,
9605 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009606
9607 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009608 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009609 }
9610 }
9611 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009612
Chris Lattnere576b912004-04-09 23:46:01 +00009613 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009614 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009615 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9616 if (FoldI)
9617 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009618 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009619
9620 if (BinaryOperator::isNot(CondVal)) {
9621 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9622 SI.setOperand(1, FalseVal);
9623 SI.setOperand(2, TrueVal);
9624 return &SI;
9625 }
9626
Chris Lattner3d69f462004-03-12 05:52:32 +00009627 return 0;
9628}
9629
Dan Gohmaneee962e2008-04-10 18:43:06 +00009630/// EnforceKnownAlignment - If the specified pointer points to an object that
9631/// we control, modify the object's alignment to PrefAlign. This isn't
9632/// often possible though. If alignment is important, a more reliable approach
9633/// is to simply align all global variables and allocation instructions to
9634/// their preferred alignment from the beginning.
9635///
9636static unsigned EnforceKnownAlignment(Value *V,
9637 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009638
Dan Gohmaneee962e2008-04-10 18:43:06 +00009639 User *U = dyn_cast<User>(V);
9640 if (!U) return Align;
9641
Dan Gohmanca178902009-07-17 20:47:02 +00009642 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009643 default: break;
9644 case Instruction::BitCast:
9645 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9646 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009647 // If all indexes are zero, it is just the alignment of the base pointer.
9648 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009649 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009650 if (!isa<Constant>(*i) ||
9651 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009652 AllZeroOperands = false;
9653 break;
9654 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009655
9656 if (AllZeroOperands) {
9657 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009658 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009659 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009660 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009661 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009662 }
9663
9664 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9665 // If there is a large requested alignment and we can, bump up the alignment
9666 // of the global.
9667 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009668 if (GV->getAlignment() >= PrefAlign)
9669 Align = GV->getAlignment();
9670 else {
9671 GV->setAlignment(PrefAlign);
9672 Align = PrefAlign;
9673 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009674 }
9675 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9676 // If there is a requested alignment and if this is an alloca, round up. We
9677 // don't do this for malloc, because some systems can't respect the request.
9678 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009679 if (AI->getAlignment() >= PrefAlign)
9680 Align = AI->getAlignment();
9681 else {
9682 AI->setAlignment(PrefAlign);
9683 Align = PrefAlign;
9684 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009685 }
9686 }
9687
9688 return Align;
9689}
9690
9691/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9692/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9693/// and it is more than the alignment of the ultimate object, see if we can
9694/// increase the alignment of the ultimate object, making this check succeed.
9695unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9696 unsigned PrefAlign) {
9697 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9698 sizeof(PrefAlign) * CHAR_BIT;
9699 APInt Mask = APInt::getAllOnesValue(BitWidth);
9700 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9701 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9702 unsigned TrailZ = KnownZero.countTrailingOnes();
9703 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9704
9705 if (PrefAlign > Align)
9706 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9707
9708 // We don't need to make any adjustment.
9709 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009710}
9711
Chris Lattnerf497b022008-01-13 23:50:23 +00009712Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009713 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009714 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009715 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009716 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009717
9718 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009719 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009720 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009721 return MI;
9722 }
9723
9724 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9725 // load/store.
9726 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9727 if (MemOpLength == 0) return 0;
9728
Chris Lattner37ac6082008-01-14 00:28:35 +00009729 // Source and destination pointer types are always "i8*" for intrinsic. See
9730 // if the size is something we can handle with a single primitive load/store.
9731 // A single load+store correctly handles overlapping memory in the memmove
9732 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009733 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009734 if (Size == 0) return MI; // Delete this mem transfer.
9735
9736 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009737 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009738
Chris Lattner37ac6082008-01-14 00:28:35 +00009739 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009740 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009741 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009742
9743 // Memcpy forces the use of i8* for the source and destination. That means
9744 // that if you're using memcpy to move one double around, you'll get a cast
9745 // from double* to i8*. We'd much rather use a double load+store rather than
9746 // an i64 load+store, here because this improves the odds that the source or
9747 // dest address will be promotable. See if we can find a better type than the
9748 // integer datatype.
9749 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9750 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009751 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009752 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9753 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009754 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009755 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9756 if (STy->getNumElements() == 1)
9757 SrcETy = STy->getElementType(0);
9758 else
9759 break;
9760 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9761 if (ATy->getNumElements() == 1)
9762 SrcETy = ATy->getElementType();
9763 else
9764 break;
9765 } else
9766 break;
9767 }
9768
Dan Gohman8f8e2692008-05-23 01:52:21 +00009769 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009770 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009771 }
9772 }
9773
9774
Chris Lattnerf497b022008-01-13 23:50:23 +00009775 // If the memcpy/memmove provides better alignment info than we can
9776 // infer, use it.
9777 SrcAlign = std::max(SrcAlign, CopyAlign);
9778 DstAlign = std::max(DstAlign, CopyAlign);
9779
9780 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9781 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009782 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9783 InsertNewInstBefore(L, *MI);
9784 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9785
9786 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009787 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009788 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009789}
Chris Lattner3d69f462004-03-12 05:52:32 +00009790
Chris Lattner69ea9d22008-04-30 06:39:11 +00009791Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9792 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009793 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009794 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009795 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009796 return MI;
9797 }
9798
9799 // Extract the length and alignment and fill if they are constant.
9800 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9801 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009802 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009803 return 0;
9804 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009805 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009806
9807 // If the length is zero, this is a no-op
9808 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9809
9810 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9811 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009812 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009813
9814 Value *Dest = MI->getDest();
Owen Andersondebcb012009-07-29 22:17:13 +00009815 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009816
9817 // Alignment 0 is identity for alignment 1 for memset, but not store.
9818 if (Alignment == 0) Alignment = 1;
9819
9820 // Extract the fill value and store.
9821 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009822 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009823 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009824
9825 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009826 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009827 return MI;
9828 }
9829
9830 return 0;
9831}
9832
9833
Chris Lattner8b0ea312006-01-13 20:11:04 +00009834/// visitCallInst - CallInst simplification. This mostly only handles folding
9835/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9836/// the heavy lifting.
9837///
Chris Lattner9fe38862003-06-19 17:00:31 +00009838Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009839 // If the caller function is nounwind, mark the call as nounwind, even if the
9840 // callee isn't.
9841 if (CI.getParent()->getParent()->doesNotThrow() &&
9842 !CI.doesNotThrow()) {
9843 CI.setDoesNotThrow();
9844 return &CI;
9845 }
9846
9847
9848
Chris Lattner8b0ea312006-01-13 20:11:04 +00009849 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9850 if (!II) return visitCallSite(&CI);
9851
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009852 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9853 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009854 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009855 bool Changed = false;
9856
9857 // memmove/cpy/set of zero bytes is a noop.
9858 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9859 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9860
Chris Lattner35b9e482004-10-12 04:52:52 +00009861 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009862 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009863 // Replace the instruction with just byte operations. We would
9864 // transform other cases to loads/stores, but we don't know if
9865 // alignment is sufficient.
9866 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009867 }
9868
Chris Lattner35b9e482004-10-12 04:52:52 +00009869 // If we have a memmove and the source operation is a constant global,
9870 // then the source and dest pointers can't alias, so we can change this
9871 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009872 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009873 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9874 if (GVSrc->isConstant()) {
9875 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009876 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9877 const Type *Tys[1];
9878 Tys[0] = CI.getOperand(3)->getType();
9879 CI.setOperand(0,
9880 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009881 Changed = true;
9882 }
Chris Lattnera935db82008-05-28 05:30:41 +00009883
9884 // memmove(x,x,size) -> noop.
9885 if (MMI->getSource() == MMI->getDest())
9886 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009887 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009888
Chris Lattner95a959d2006-03-06 20:18:44 +00009889 // If we can determine a pointer alignment that is bigger than currently
9890 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009891 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009892 if (Instruction *I = SimplifyMemTransfer(MI))
9893 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009894 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9895 if (Instruction *I = SimplifyMemSet(MSI))
9896 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009897 }
9898
Chris Lattner8b0ea312006-01-13 20:11:04 +00009899 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009900 }
9901
9902 switch (II->getIntrinsicID()) {
9903 default: break;
9904 case Intrinsic::bswap:
9905 // bswap(bswap(x)) -> x
9906 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9907 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9908 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9909 break;
9910 case Intrinsic::ppc_altivec_lvx:
9911 case Intrinsic::ppc_altivec_lvxl:
9912 case Intrinsic::x86_sse_loadu_ps:
9913 case Intrinsic::x86_sse2_loadu_pd:
9914 case Intrinsic::x86_sse2_loadu_dq:
9915 // Turn PPC lvx -> load if the pointer is known aligned.
9916 // Turn X86 loadups -> load if the pointer is known aligned.
9917 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9918 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersondebcb012009-07-29 22:17:13 +00009919 PointerType::getUnqual(II->getType()),
Chris Lattner0521e3c2008-06-18 04:33:20 +00009920 CI);
9921 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009922 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009923 break;
9924 case Intrinsic::ppc_altivec_stvx:
9925 case Intrinsic::ppc_altivec_stvxl:
9926 // Turn stvx -> store if the pointer is known aligned.
9927 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9928 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009929 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009930 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9931 return new StoreInst(II->getOperand(1), Ptr);
9932 }
9933 break;
9934 case Intrinsic::x86_sse_storeu_ps:
9935 case Intrinsic::x86_sse2_storeu_pd:
9936 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009937 // Turn X86 storeu -> store if the pointer is known aligned.
9938 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9939 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009940 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009941 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9942 return new StoreInst(II->getOperand(2), Ptr);
9943 }
9944 break;
9945
9946 case Intrinsic::x86_sse_cvttss2si: {
9947 // These intrinsics only demands the 0th element of its input vector. If
9948 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009949 unsigned VWidth =
9950 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9951 APInt DemandedElts(VWidth, 1);
9952 APInt UndefElts(VWidth, 0);
9953 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009954 UndefElts)) {
9955 II->setOperand(1, V);
9956 return II;
9957 }
9958 break;
9959 }
9960
9961 case Intrinsic::ppc_altivec_vperm:
9962 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9963 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9964 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009965
Chris Lattner0521e3c2008-06-18 04:33:20 +00009966 // Check that all of the elements are integer constants or undefs.
9967 bool AllEltsOk = true;
9968 for (unsigned i = 0; i != 16; ++i) {
9969 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9970 !isa<UndefValue>(Mask->getOperand(i))) {
9971 AllEltsOk = false;
9972 break;
9973 }
9974 }
9975
9976 if (AllEltsOk) {
9977 // Cast the input vectors to byte vectors.
9978 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9979 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009980 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009981
Chris Lattner0521e3c2008-06-18 04:33:20 +00009982 // Only extract each element once.
9983 Value *ExtractedElts[32];
9984 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9985
Chris Lattnere2ed0572006-04-06 19:19:17 +00009986 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009987 if (isa<UndefValue>(Mask->getOperand(i)))
9988 continue;
9989 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9990 Idx &= 31; // Match the hardware behavior.
9991
9992 if (ExtractedElts[Idx] == 0) {
9993 Instruction *Elt =
Eric Christophera3500da2009-07-25 02:28:41 +00009994 ExtractElementInst::Create(Idx < 16 ? Op0 : Op1,
Owen Anderson1d0be152009-08-13 21:58:54 +00009995 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false), "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009996 InsertNewInstBefore(Elt, CI);
9997 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009998 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009999
Chris Lattner0521e3c2008-06-18 04:33:20 +000010000 // Insert this value into the result vector.
10001 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
Owen Anderson1d0be152009-08-13 21:58:54 +000010002 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
Owen Anderson9adc0ab2009-07-14 23:09:55 +000010003 "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +000010004 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +000010005 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010006 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010007 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010008 }
10009 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +000010010
Chris Lattner0521e3c2008-06-18 04:33:20 +000010011 case Intrinsic::stackrestore: {
10012 // If the save is right next to the restore, remove the restore. This can
10013 // happen when variable allocas are DCE'd.
10014 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10015 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10016 BasicBlock::iterator BI = SS;
10017 if (&*++BI == II)
10018 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +000010019 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010020 }
10021
10022 // Scan down this block to see if there is another stack restore in the
10023 // same block without an intervening call/alloca.
10024 BasicBlock::iterator BI = II;
10025 TerminatorInst *TI = II->getParent()->getTerminator();
10026 bool CannotRemove = false;
10027 for (++BI; &*BI != TI; ++BI) {
10028 if (isa<AllocaInst>(BI)) {
10029 CannotRemove = true;
10030 break;
10031 }
Chris Lattneraa0bf522008-06-25 05:59:28 +000010032 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10033 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10034 // If there is a stackrestore below this one, remove this one.
10035 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10036 return EraseInstFromFunction(CI);
10037 // Otherwise, ignore the intrinsic.
10038 } else {
10039 // If we found a non-intrinsic call, we can't remove the stack
10040 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010041 CannotRemove = true;
10042 break;
10043 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010044 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010045 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010046
10047 // If the stack restore is in a return/unwind block and if there are no
10048 // allocas or calls between the restore and the return, nuke the restore.
10049 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10050 return EraseInstFromFunction(CI);
10051 break;
10052 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010053 }
10054
Chris Lattner8b0ea312006-01-13 20:11:04 +000010055 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010056}
10057
10058// InvokeInst simplification
10059//
10060Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010061 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010062}
10063
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010064/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10065/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010066static bool isSafeToEliminateVarargsCast(const CallSite CS,
10067 const CastInst * const CI,
10068 const TargetData * const TD,
10069 const int ix) {
10070 if (!CI->isLosslessCast())
10071 return false;
10072
10073 // The size of ByVal arguments is derived from the type, so we
10074 // can't change to a type with a different size. If the size were
10075 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010076 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010077 return true;
10078
10079 const Type* SrcTy =
10080 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10081 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10082 if (!SrcTy->isSized() || !DstTy->isSized())
10083 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010084 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010085 return false;
10086 return true;
10087}
10088
Chris Lattnera44d8a22003-10-07 22:32:43 +000010089// visitCallSite - Improvements for call and invoke instructions.
10090//
10091Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010092 bool Changed = false;
10093
10094 // If the callee is a constexpr cast of a function, attempt to move the cast
10095 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010096 if (transformConstExprCastCall(CS)) return 0;
10097
Chris Lattner6c266db2003-10-07 22:54:13 +000010098 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010099
Chris Lattner08b22ec2005-05-13 07:09:09 +000010100 if (Function *CalleeF = dyn_cast<Function>(Callee))
10101 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10102 Instruction *OldCall = CS.getInstruction();
10103 // If the call and callee calling conventions don't match, this call must
10104 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010105 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +000010106 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Owen Andersond672ecb2009-07-03 00:17:18 +000010107 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +000010108 if (!OldCall->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010109 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010110 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10111 return EraseInstFromFunction(*OldCall);
10112 return 0;
10113 }
10114
Chris Lattner17be6352004-10-18 02:59:09 +000010115 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10116 // This instruction is not reachable, just remove it. We insert a store to
10117 // undef so that we know that this code is not reachable, despite the fact
10118 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010119 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +000010120 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Chris Lattner17be6352004-10-18 02:59:09 +000010121 CS.getInstruction());
10122
10123 if (!CS.getInstruction()->use_empty())
10124 CS.getInstruction()->
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010125 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010126
10127 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10128 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010129 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010130 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010131 }
Chris Lattner17be6352004-10-18 02:59:09 +000010132 return EraseInstFromFunction(*CS.getInstruction());
10133 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010134
Duncan Sandscdb6d922007-09-17 10:26:40 +000010135 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10136 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10137 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10138 return transformCallThroughTrampoline(CS);
10139
Chris Lattner6c266db2003-10-07 22:54:13 +000010140 const PointerType *PTy = cast<PointerType>(Callee->getType());
10141 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10142 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010143 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010144 // See if we can optimize any arguments passed through the varargs area of
10145 // the call.
10146 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010147 E = CS.arg_end(); I != E; ++I, ++ix) {
10148 CastInst *CI = dyn_cast<CastInst>(*I);
10149 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10150 *I = CI->getOperand(0);
10151 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010152 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010153 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010154 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010155
Duncan Sandsf0c33542007-12-19 21:13:37 +000010156 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010157 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010158 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010159 Changed = true;
10160 }
10161
Chris Lattner6c266db2003-10-07 22:54:13 +000010162 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010163}
10164
Chris Lattner9fe38862003-06-19 17:00:31 +000010165// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10166// attempt to move the cast to the arguments of the call/invoke.
10167//
10168bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10169 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10170 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010171 if (CE->getOpcode() != Instruction::BitCast ||
10172 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010173 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010174 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010175 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010176 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010177
10178 // Okay, this is a cast from a function to a different type. Unless doing so
10179 // would cause a type conversion of one of our arguments, change this call to
10180 // be a direct call with arguments casted to the appropriate types.
10181 //
10182 const FunctionType *FT = Callee->getFunctionType();
10183 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010184 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010185
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010186 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010187 return false; // TODO: Handle multiple return values.
10188
Chris Lattnerf78616b2004-01-14 06:06:08 +000010189 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010190 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010191 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010192 // Conversion is ok if changing from one pointer type to another or from
10193 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010194 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010195 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010196 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010197 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010198 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010199
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010200 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010201 // void -> non-void is handled specially
Owen Anderson1d0be152009-08-13 21:58:54 +000010202 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010203 return false; // Cannot transform this return value.
10204
Chris Lattner58d74912008-03-12 17:45:29 +000010205 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010206 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010207 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010208 return false; // Attribute not compatible with transformed value.
10209 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010210
Chris Lattnerf78616b2004-01-14 06:06:08 +000010211 // If the callsite is an invoke instruction, and the return value is used by
10212 // a PHI node in a successor, we cannot change the return type of the call
10213 // because there is no place to put the cast instruction (without breaking
10214 // the critical edge). Bail out in this case.
10215 if (!Caller->use_empty())
10216 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10217 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10218 UI != E; ++UI)
10219 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10220 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010221 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010222 return false;
10223 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010224
10225 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10226 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010227
Chris Lattner9fe38862003-06-19 17:00:31 +000010228 CallSite::arg_iterator AI = CS.arg_begin();
10229 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10230 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010231 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010232
10233 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010234 return false; // Cannot transform this parameter value.
10235
Devang Patel19c87462008-09-26 22:53:05 +000010236 if (CallerPAL.getParamAttributes(i + 1)
10237 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010238 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010239
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010240 // Converting from one pointer type to another or between a pointer and an
10241 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010242 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010243 (TD && ((isa<PointerType>(ParamTy) ||
10244 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10245 (isa<PointerType>(ActTy) ||
10246 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010247 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010248 }
10249
10250 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010251 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010252 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010253
Chris Lattner58d74912008-03-12 17:45:29 +000010254 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10255 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010256 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010257 // won't be dropping them. Check that these extra arguments have attributes
10258 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010259 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10260 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010261 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010262 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010263 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010264 return false;
10265 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010266
Chris Lattner9fe38862003-06-19 17:00:31 +000010267 // Okay, we decided that this is a safe thing to do: go ahead and start
10268 // inserting cast instructions as necessary...
10269 std::vector<Value*> Args;
10270 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010271 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010272 attrVec.reserve(NumCommonArgs);
10273
10274 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010275 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010276
10277 // If the return value is not being used, the type may not be compatible
10278 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010279 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010280
10281 // Add the new return attributes.
10282 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010283 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010284
10285 AI = CS.arg_begin();
10286 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10287 const Type *ParamTy = FT->getParamType(i);
10288 if ((*AI)->getType() == ParamTy) {
10289 Args.push_back(*AI);
10290 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010291 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010292 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010293 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010294 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010295 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010296
10297 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010298 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010299 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010300 }
10301
10302 // If the function takes more arguments than the call was taking, add them
10303 // now...
10304 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010305 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010306
10307 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010308 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010309 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010310 errs() << "WARNING: While resolving call to function '"
10311 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010312 } else {
10313 // Add all of the arguments in their promoted form to the arg list...
10314 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10315 const Type *PTy = getPromotedType((*AI)->getType());
10316 if (PTy != (*AI)->getType()) {
10317 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010318 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10319 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010320 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010321 InsertNewInstBefore(Cast, *Caller);
10322 Args.push_back(Cast);
10323 } else {
10324 Args.push_back(*AI);
10325 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010326
Duncan Sandse1e520f2008-01-13 08:02:44 +000010327 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010328 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010329 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010330 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010331 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010332 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010333
Devang Patel19c87462008-09-26 22:53:05 +000010334 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10335 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10336
Owen Anderson1d0be152009-08-13 21:58:54 +000010337 if (NewRetTy == Type::getVoidTy(*Context))
Chris Lattner6934a042007-02-11 01:23:03 +000010338 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010339
Eric Christophera66297a2009-07-25 02:45:27 +000010340 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10341 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010342
Chris Lattner9fe38862003-06-19 17:00:31 +000010343 Instruction *NC;
10344 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010345 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010346 Args.begin(), Args.end(),
10347 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010348 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010349 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010350 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010351 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10352 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010353 CallInst *CI = cast<CallInst>(Caller);
10354 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010355 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010356 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010357 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010358 }
10359
Chris Lattner6934a042007-02-11 01:23:03 +000010360 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010361 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010362 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010363 if (NV->getType() != Type::getVoidTy(*Context)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010364 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010365 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010366 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010367
10368 // If this is an invoke instruction, we should insert it after the first
10369 // non-phi, instruction in the normal successor block.
10370 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010371 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010372 InsertNewInstBefore(NC, *I);
10373 } else {
10374 // Otherwise, it's a call, just insert cast right after the call instr
10375 InsertNewInstBefore(NC, *Caller);
10376 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010377 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010378 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010379 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010380 }
10381 }
10382
Owen Anderson1d0be152009-08-13 21:58:54 +000010383 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010384 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010385 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010386 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010387 return true;
10388}
10389
Duncan Sandscdb6d922007-09-17 10:26:40 +000010390// transformCallThroughTrampoline - Turn a call to a function created by the
10391// init_trampoline intrinsic into a direct call to the underlying function.
10392//
10393Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10394 Value *Callee = CS.getCalledValue();
10395 const PointerType *PTy = cast<PointerType>(Callee->getType());
10396 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010397 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010398
10399 // If the call already has the 'nest' attribute somewhere then give up -
10400 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010401 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010402 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010403
10404 IntrinsicInst *Tramp =
10405 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10406
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010407 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010408 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10409 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10410
Devang Patel05988662008-09-25 21:00:45 +000010411 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010412 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010413 unsigned NestIdx = 1;
10414 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010415 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010416
10417 // Look for a parameter marked with the 'nest' attribute.
10418 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10419 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010420 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010421 // Record the parameter type and any other attributes.
10422 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010423 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010424 break;
10425 }
10426
10427 if (NestTy) {
10428 Instruction *Caller = CS.getInstruction();
10429 std::vector<Value*> NewArgs;
10430 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10431
Devang Patel05988662008-09-25 21:00:45 +000010432 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010433 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010434
Duncan Sandscdb6d922007-09-17 10:26:40 +000010435 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010436 // mean appending it. Likewise for attributes.
10437
Devang Patel19c87462008-09-26 22:53:05 +000010438 // Add any result attributes.
10439 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010440 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010441
Duncan Sandscdb6d922007-09-17 10:26:40 +000010442 {
10443 unsigned Idx = 1;
10444 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10445 do {
10446 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010447 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010448 Value *NestVal = Tramp->getOperand(3);
10449 if (NestVal->getType() != NestTy)
10450 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10451 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010452 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010453 }
10454
10455 if (I == E)
10456 break;
10457
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010458 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010459 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010460 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010461 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010462 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010463
10464 ++Idx, ++I;
10465 } while (1);
10466 }
10467
Devang Patel19c87462008-09-26 22:53:05 +000010468 // Add any function attributes.
10469 if (Attributes Attr = Attrs.getFnAttributes())
10470 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10471
Duncan Sandscdb6d922007-09-17 10:26:40 +000010472 // The trampoline may have been bitcast to a bogus type (FTy).
10473 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010474 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010475
Duncan Sandscdb6d922007-09-17 10:26:40 +000010476 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010477 NewTypes.reserve(FTy->getNumParams()+1);
10478
Duncan Sandscdb6d922007-09-17 10:26:40 +000010479 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010480 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010481 {
10482 unsigned Idx = 1;
10483 FunctionType::param_iterator I = FTy->param_begin(),
10484 E = FTy->param_end();
10485
10486 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010487 if (Idx == NestIdx)
10488 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010489 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010490
10491 if (I == E)
10492 break;
10493
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010494 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010495 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010496
10497 ++Idx, ++I;
10498 } while (1);
10499 }
10500
10501 // Replace the trampoline call with a direct call. Let the generic
10502 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010503 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010504 FTy->isVarArg());
10505 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010506 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010507 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010508 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010509 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10510 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010511
10512 Instruction *NewCaller;
10513 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010514 NewCaller = InvokeInst::Create(NewCallee,
10515 II->getNormalDest(), II->getUnwindDest(),
10516 NewArgs.begin(), NewArgs.end(),
10517 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010518 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010519 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010520 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010521 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10522 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010523 if (cast<CallInst>(Caller)->isTailCall())
10524 cast<CallInst>(NewCaller)->setTailCall();
10525 cast<CallInst>(NewCaller)->
10526 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010527 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010528 }
Owen Anderson1d0be152009-08-13 21:58:54 +000010529 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010530 Caller->replaceAllUsesWith(NewCaller);
10531 Caller->eraseFromParent();
10532 RemoveFromWorkList(Caller);
10533 return 0;
10534 }
10535 }
10536
10537 // Replace the trampoline call with a direct call. Since there is no 'nest'
10538 // parameter, there is no need to adjust the argument list. Let the generic
10539 // code sort out any function type mismatches.
10540 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010541 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010542 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010543 CS.setCalledFunction(NewCallee);
10544 return CS.getInstruction();
10545}
10546
Chris Lattner7da52b22006-11-01 04:51:18 +000010547/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10548/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10549/// and a single binop.
10550Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10551 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010552 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010553 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010554 Value *LHSVal = FirstInst->getOperand(0);
10555 Value *RHSVal = FirstInst->getOperand(1);
10556
10557 const Type *LHSType = LHSVal->getType();
10558 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010559
10560 // Scan to see if all operands are the same opcode, all have one use, and all
10561 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010562 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010563 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010564 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010565 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010566 // types or GEP's with different index types.
10567 I->getOperand(0)->getType() != LHSType ||
10568 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010569 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010570
10571 // If they are CmpInst instructions, check their predicates
10572 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10573 if (cast<CmpInst>(I)->getPredicate() !=
10574 cast<CmpInst>(FirstInst)->getPredicate())
10575 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010576
10577 // Keep track of which operand needs a phi node.
10578 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10579 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010580 }
10581
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010582 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010583
Chris Lattner7da52b22006-11-01 04:51:18 +000010584 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010585 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010586 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010587 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010588 NewLHS = PHINode::Create(LHSType,
10589 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010590 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10591 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010592 InsertNewInstBefore(NewLHS, PN);
10593 LHSVal = NewLHS;
10594 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010595
10596 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010597 NewRHS = PHINode::Create(RHSType,
10598 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010599 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10600 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010601 InsertNewInstBefore(NewRHS, PN);
10602 RHSVal = NewRHS;
10603 }
10604
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010605 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010606 if (NewLHS || NewRHS) {
10607 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10608 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10609 if (NewLHS) {
10610 Value *NewInLHS = InInst->getOperand(0);
10611 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10612 }
10613 if (NewRHS) {
10614 Value *NewInRHS = InInst->getOperand(1);
10615 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10616 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010617 }
10618 }
10619
Chris Lattner7da52b22006-11-01 04:51:18 +000010620 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010621 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010622 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010623 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010624 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010625}
10626
Chris Lattner05f18922008-12-01 02:34:36 +000010627Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10628 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10629
10630 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10631 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010632 // This is true if all GEP bases are allocas and if all indices into them are
10633 // constants.
10634 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010635
10636 // Scan to see if all operands are the same opcode, all have one use, and all
10637 // kill their operands (i.e. the operands have one use).
10638 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10639 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10640 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10641 GEP->getNumOperands() != FirstInst->getNumOperands())
10642 return 0;
10643
Chris Lattner36d3e322009-02-21 00:46:50 +000010644 // Keep track of whether or not all GEPs are of alloca pointers.
10645 if (AllBasePointersAreAllocas &&
10646 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10647 !GEP->hasAllConstantIndices()))
10648 AllBasePointersAreAllocas = false;
10649
Chris Lattner05f18922008-12-01 02:34:36 +000010650 // Compare the operand lists.
10651 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10652 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10653 continue;
10654
10655 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10656 // if one of the PHIs has a constant for the index. The index may be
10657 // substantially cheaper to compute for the constants, so making it a
10658 // variable index could pessimize the path. This also handles the case
10659 // for struct indices, which must always be constant.
10660 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10661 isa<ConstantInt>(GEP->getOperand(op)))
10662 return 0;
10663
10664 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10665 return 0;
10666 FixedOperands[op] = 0; // Needs a PHI.
10667 }
10668 }
10669
Chris Lattner36d3e322009-02-21 00:46:50 +000010670 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010671 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010672 // offset calculation, but all the predecessors will have to materialize the
10673 // stack address into a register anyway. We'd actually rather *clone* the
10674 // load up into the predecessors so that we have a load of a gep of an alloca,
10675 // which can usually all be folded into the load.
10676 if (AllBasePointersAreAllocas)
10677 return 0;
10678
Chris Lattner05f18922008-12-01 02:34:36 +000010679 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10680 // that is variable.
10681 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10682
10683 bool HasAnyPHIs = false;
10684 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10685 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10686 Value *FirstOp = FirstInst->getOperand(i);
10687 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10688 FirstOp->getName()+".pn");
10689 InsertNewInstBefore(NewPN, PN);
10690
10691 NewPN->reserveOperandSpace(e);
10692 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10693 OperandPhis[i] = NewPN;
10694 FixedOperands[i] = NewPN;
10695 HasAnyPHIs = true;
10696 }
10697
10698
10699 // Add all operands to the new PHIs.
10700 if (HasAnyPHIs) {
10701 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10702 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10703 BasicBlock *InBB = PN.getIncomingBlock(i);
10704
10705 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10706 if (PHINode *OpPhi = OperandPhis[op])
10707 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10708 }
10709 }
10710
10711 Value *Base = FixedOperands[0];
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010712 GetElementPtrInst *GEP =
10713 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10714 FixedOperands.end());
10715 if (cast<GEPOperator>(FirstInst)->isInBounds())
10716 cast<GEPOperator>(GEP)->setIsInBounds(true);
10717 return GEP;
Chris Lattner05f18922008-12-01 02:34:36 +000010718}
10719
10720
Chris Lattner21550882009-02-23 05:56:17 +000010721/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10722/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010723/// obvious the value of the load is not changed from the point of the load to
10724/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010725///
10726/// Finally, it is safe, but not profitable, to sink a load targetting a
10727/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10728/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010729static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010730 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10731
10732 for (++BBI; BBI != E; ++BBI)
10733 if (BBI->mayWriteToMemory())
10734 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010735
10736 // Check for non-address taken alloca. If not address-taken already, it isn't
10737 // profitable to do this xform.
10738 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10739 bool isAddressTaken = false;
10740 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10741 UI != E; ++UI) {
10742 if (isa<LoadInst>(UI)) continue;
10743 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10744 // If storing TO the alloca, then the address isn't taken.
10745 if (SI->getOperand(1) == AI) continue;
10746 }
10747 isAddressTaken = true;
10748 break;
10749 }
10750
Chris Lattner36d3e322009-02-21 00:46:50 +000010751 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010752 return false;
10753 }
10754
Chris Lattner36d3e322009-02-21 00:46:50 +000010755 // If this load is a load from a GEP with a constant offset from an alloca,
10756 // then we don't want to sink it. In its present form, it will be
10757 // load [constant stack offset]. Sinking it will cause us to have to
10758 // materialize the stack addresses in each predecessor in a register only to
10759 // do a shared load from register in the successor.
10760 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10761 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10762 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10763 return false;
10764
Chris Lattner76c73142006-11-01 07:13:54 +000010765 return true;
10766}
10767
Chris Lattner9fe38862003-06-19 17:00:31 +000010768
Chris Lattnerbac32862004-11-14 19:13:23 +000010769// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10770// operator and they all are only used by the PHI, PHI together their
10771// inputs, and do the operation once, to the result of the PHI.
10772Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10773 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10774
10775 // Scan the instruction, looking for input operations that can be folded away.
10776 // If all input operands to the phi are the same instruction (e.g. a cast from
10777 // the same type or "+42") we can pull the operation through the PHI, reducing
10778 // code size and simplifying code.
10779 Constant *ConstantOp = 0;
10780 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010781 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010782 if (isa<CastInst>(FirstInst)) {
10783 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010784 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010785 // Can fold binop, compare or shift here if the RHS is a constant,
10786 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010787 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010788 if (ConstantOp == 0)
10789 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010790 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10791 isVolatile = LI->isVolatile();
10792 // We can't sink the load if the loaded value could be modified between the
10793 // load and the PHI.
10794 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010795 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010796 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010797
10798 // If the PHI is of volatile loads and the load block has multiple
10799 // successors, sinking it would remove a load of the volatile value from
10800 // the path through the other successor.
10801 if (isVolatile &&
10802 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10803 return 0;
10804
Chris Lattner9c080502006-11-01 07:43:41 +000010805 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010806 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010807 } else {
10808 return 0; // Cannot fold this operation.
10809 }
10810
10811 // Check to see if all arguments are the same operation.
10812 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10813 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10814 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010815 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010816 return 0;
10817 if (CastSrcTy) {
10818 if (I->getOperand(0)->getType() != CastSrcTy)
10819 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010820 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010821 // We can't sink the load if the loaded value could be modified between
10822 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010823 if (LI->isVolatile() != isVolatile ||
10824 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010825 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010826 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010827
Chris Lattner71042962008-07-08 17:18:32 +000010828 // If the PHI is of volatile loads and the load block has multiple
10829 // successors, sinking it would remove a load of the volatile value from
10830 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010831 if (isVolatile &&
10832 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10833 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010834
Chris Lattnerbac32862004-11-14 19:13:23 +000010835 } else if (I->getOperand(1) != ConstantOp) {
10836 return 0;
10837 }
10838 }
10839
10840 // Okay, they are all the same operation. Create a new PHI node of the
10841 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010842 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10843 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010844 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010845
10846 Value *InVal = FirstInst->getOperand(0);
10847 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010848
10849 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010850 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10851 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10852 if (NewInVal != InVal)
10853 InVal = 0;
10854 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10855 }
10856
10857 Value *PhiVal;
10858 if (InVal) {
10859 // The new PHI unions all of the same values together. This is really
10860 // common, so we handle it intelligently here for compile-time speed.
10861 PhiVal = InVal;
10862 delete NewPN;
10863 } else {
10864 InsertNewInstBefore(NewPN, PN);
10865 PhiVal = NewPN;
10866 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010867
Chris Lattnerbac32862004-11-14 19:13:23 +000010868 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010869 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010870 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010871 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010872 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010873 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010874 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010875 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010876 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10877
10878 // If this was a volatile load that we are merging, make sure to loop through
10879 // and mark all the input loads as non-volatile. If we don't do this, we will
10880 // insert a new volatile load and the old ones will not be deletable.
10881 if (isVolatile)
10882 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10883 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10884
10885 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010886}
Chris Lattnera1be5662002-05-02 17:06:02 +000010887
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010888/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10889/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010890static bool DeadPHICycle(PHINode *PN,
10891 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010892 if (PN->use_empty()) return true;
10893 if (!PN->hasOneUse()) return false;
10894
10895 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010896 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010897 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010898
10899 // Don't scan crazily complex things.
10900 if (PotentiallyDeadPHIs.size() == 16)
10901 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010902
10903 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10904 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010905
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010906 return false;
10907}
10908
Chris Lattnercf5008a2007-11-06 21:52:06 +000010909/// PHIsEqualValue - Return true if this phi node is always equal to
10910/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10911/// z = some value; x = phi (y, z); y = phi (x, z)
10912static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10913 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10914 // See if we already saw this PHI node.
10915 if (!ValueEqualPHIs.insert(PN))
10916 return true;
10917
10918 // Don't scan crazily complex things.
10919 if (ValueEqualPHIs.size() == 16)
10920 return false;
10921
10922 // Scan the operands to see if they are either phi nodes or are equal to
10923 // the value.
10924 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10925 Value *Op = PN->getIncomingValue(i);
10926 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10927 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10928 return false;
10929 } else if (Op != NonPhiInVal)
10930 return false;
10931 }
10932
10933 return true;
10934}
10935
10936
Chris Lattner473945d2002-05-06 18:06:38 +000010937// PHINode simplification
10938//
Chris Lattner7e708292002-06-25 16:13:24 +000010939Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010940 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010941 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010942
Owen Anderson7e057142006-07-10 22:03:18 +000010943 if (Value *V = PN.hasConstantValue())
10944 return ReplaceInstUsesWith(PN, V);
10945
Owen Anderson7e057142006-07-10 22:03:18 +000010946 // If all PHI operands are the same operation, pull them through the PHI,
10947 // reducing code size.
10948 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010949 isa<Instruction>(PN.getIncomingValue(1)) &&
10950 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10951 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10952 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10953 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010954 PN.getIncomingValue(0)->hasOneUse())
10955 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10956 return Result;
10957
10958 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10959 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10960 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010961 if (PN.hasOneUse()) {
10962 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10963 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010964 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010965 PotentiallyDeadPHIs.insert(&PN);
10966 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010967 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010968 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010969
10970 // If this phi has a single use, and if that use just computes a value for
10971 // the next iteration of a loop, delete the phi. This occurs with unused
10972 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10973 // common case here is good because the only other things that catch this
10974 // are induction variable analysis (sometimes) and ADCE, which is only run
10975 // late.
10976 if (PHIUser->hasOneUse() &&
10977 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10978 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010979 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010980 }
10981 }
Owen Anderson7e057142006-07-10 22:03:18 +000010982
Chris Lattnercf5008a2007-11-06 21:52:06 +000010983 // We sometimes end up with phi cycles that non-obviously end up being the
10984 // same value, for example:
10985 // z = some value; x = phi (y, z); y = phi (x, z)
10986 // where the phi nodes don't necessarily need to be in the same block. Do a
10987 // quick check to see if the PHI node only contains a single non-phi value, if
10988 // so, scan to see if the phi cycle is actually equal to that value.
10989 {
10990 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10991 // Scan for the first non-phi operand.
10992 while (InValNo != NumOperandVals &&
10993 isa<PHINode>(PN.getIncomingValue(InValNo)))
10994 ++InValNo;
10995
10996 if (InValNo != NumOperandVals) {
10997 Value *NonPhiInVal = PN.getOperand(InValNo);
10998
10999 // Scan the rest of the operands to see if there are any conflicts, if so
11000 // there is no need to recursively scan other phis.
11001 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11002 Value *OpVal = PN.getIncomingValue(InValNo);
11003 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11004 break;
11005 }
11006
11007 // If we scanned over all operands, then we have one unique value plus
11008 // phi values. Scan PHI nodes to see if they all merge in each other or
11009 // the value.
11010 if (InValNo == NumOperandVals) {
11011 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11012 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11013 return ReplaceInstUsesWith(PN, NonPhiInVal);
11014 }
11015 }
11016 }
Chris Lattner60921c92003-12-19 05:58:40 +000011017 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000011018}
11019
Chris Lattner7e708292002-06-25 16:13:24 +000011020Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000011021 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000011022 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000011023 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011024 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000011025 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011026
Chris Lattnere87597f2004-10-16 18:11:37 +000011027 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011028 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011029
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011030 bool HasZeroPointerIndex = false;
11031 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11032 HasZeroPointerIndex = C->isNullValue();
11033
11034 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011035 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011036
Chris Lattner28977af2004-04-05 01:30:19 +000011037 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000011038 if (TD) {
11039 bool MadeChange = false;
11040 unsigned PtrSize = TD->getPointerSizeInBits();
11041
11042 gep_type_iterator GTI = gep_type_begin(GEP);
11043 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11044 I != E; ++I, ++GTI) {
11045 if (!isa<SequentialType>(*GTI)) continue;
11046
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011047 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000011048 // to what we need. If narrower, sign-extend it to what we need. This
11049 // explicit cast can make subsequent optimizations more obvious.
11050 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
11051
11052 if (OpBits == PtrSize)
11053 continue;
11054
11055 Instruction::CastOps Opc =
11056 OpBits > PtrSize ? Instruction::Trunc : Instruction::SExt;
11057 *I = InsertCastBefore(Opc, *I, TD->getIntPtrType(GEP.getContext()), GEP);
11058 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000011059 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000011060 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011061 }
Chris Lattner28977af2004-04-05 01:30:19 +000011062
Chris Lattner90ac28c2002-08-02 19:29:35 +000011063 // Combine Indices - If the source pointer to this getelementptr instruction
11064 // is a getelementptr instruction, combine the indices of the two
11065 // getelementptr instructions into a single instruction.
11066 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011067 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000011068 // Note that if our source is a gep chain itself that we wait for that
11069 // chain to be resolved before we perform this transformation. This
11070 // avoids us creating a TON of code in some cases.
11071 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011072 if (GetElementPtrInst *SrcGEP =
11073 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11074 if (SrcGEP->getNumOperands() == 2)
11075 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000011076
Chris Lattner72588fc2007-02-15 22:48:32 +000011077 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011078
11079 // Find out whether the last index in the source GEP is a sequential idx.
11080 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000011081 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11082 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011083 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011084
Chris Lattner90ac28c2002-08-02 19:29:35 +000011085 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011086 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011087 // Replace: gep (gep %P, long B), long A, ...
11088 // With: T = long A+B; gep %P, T, ...
11089 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011090 Value *Sum;
11091 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11092 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000011093 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011094 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000011095 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011096 Sum = SO1;
11097 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000011098 // If they aren't the same type, then the input hasn't been processed
11099 // by the loop above yet (which canonicalizes sequential index types to
11100 // intptr_t). Just avoid transforming this until the input has been
11101 // normalized.
11102 if (SO1->getType() != GO1->getType())
11103 return 0;
Chris Lattner620ce142004-05-07 22:09:22 +000011104 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Chris Lattnerccf4b342009-08-30 04:49:01 +000011105 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
Chris Lattner620ce142004-05-07 22:09:22 +000011106 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011107 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011108 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011109 }
Chris Lattner28977af2004-04-05 01:30:19 +000011110 }
Chris Lattner620ce142004-05-07 22:09:22 +000011111
Chris Lattnerab984842009-08-30 05:30:55 +000011112 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011113 if (Src->getNumOperands() == 2) {
11114 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000011115 GEP.setOperand(1, Sum);
11116 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000011117 }
Chris Lattnerab984842009-08-30 05:30:55 +000011118 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011119 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000011120 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000011121 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011122 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011123 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011124 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000011125 Indices.append(Src->op_begin()+1, Src->op_end());
11126 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011127 }
11128
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011129 if (!Indices.empty()) {
Chris Lattnerccf4b342009-08-30 04:49:01 +000011130 GetElementPtrInst *NewGEP =
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011131 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000011132 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000011133 if (cast<GEPOperator>(&GEP)->isInBounds() && Src->isInBounds())
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011134 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11135 return NewGEP;
11136 }
Chris Lattner6e24d832009-08-30 05:00:50 +000011137 }
11138
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011139 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11140 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011141 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
11142
11143 if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011144 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11145 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011146 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011147 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11148 // into : GEP i8* X, ...
11149 //
Chris Lattnereed48272005-09-13 00:40:14 +000011150 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011151 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11152 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011153 if (const ArrayType *CATy =
11154 dyn_cast<ArrayType>(CPTy->getElementType())) {
11155 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11156 if (CATy->getElementType() == XTy->getElementType()) {
11157 // -> GEP i8* X, ...
11158 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011159 GetElementPtrInst *NewGEP =
11160 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11161 GEP.getName());
11162 if (cast<GEPOperator>(&GEP)->isInBounds())
11163 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11164 return NewGEP;
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011165 } else if (const ArrayType *XATy =
11166 dyn_cast<ArrayType>(XTy->getElementType())) {
11167 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011168 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011169 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011170 // At this point, we know that the cast source type is a pointer
11171 // to an array of the same type as the destination pointer
11172 // array. Because the array type is never stepped over (there
11173 // is a leading zero) we can fold the cast into this GEP.
11174 GEP.setOperand(0, X);
11175 return &GEP;
11176 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011177 }
11178 }
Chris Lattnereed48272005-09-13 00:40:14 +000011179 } else if (GEP.getNumOperands() == 2) {
11180 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011181 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11182 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011183 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11184 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011185 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011186 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11187 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011188 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011189 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011190 Idx[1] = GEP.getOperand(1);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011191 GetElementPtrInst *NewGEP =
11192 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11193 if (cast<GEPOperator>(&GEP)->isInBounds())
11194 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11195 Value *V = InsertNewInstBefore(NewGEP, GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011196 // V and GEP are both pointer types --> BitCast
11197 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011198 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011199
11200 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011201 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011202 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011203 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011204
Owen Anderson1d0be152009-08-13 21:58:54 +000011205 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011206 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011207 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011208
11209 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11210 // allow either a mul, shift, or constant here.
11211 Value *NewIdx = 0;
11212 ConstantInt *Scale = 0;
11213 if (ArrayEltSize == 1) {
11214 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011215 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011216 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011217 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011218 Scale = CI;
11219 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11220 if (Inst->getOpcode() == Instruction::Shl &&
11221 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011222 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11223 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011224 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011225 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011226 NewIdx = Inst->getOperand(0);
11227 } else if (Inst->getOpcode() == Instruction::Mul &&
11228 isa<ConstantInt>(Inst->getOperand(1))) {
11229 Scale = cast<ConstantInt>(Inst->getOperand(1));
11230 NewIdx = Inst->getOperand(0);
11231 }
11232 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011233
Chris Lattner7835cdd2005-09-13 18:36:04 +000011234 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011235 // out, perform the transformation. Note, we don't know whether Scale is
11236 // signed or not. We'll use unsigned version of division/modulo
11237 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011238 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011239 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011240 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011241 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011242 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011243 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11244 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011245 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011246 NewIdx = InsertNewInstBefore(Sc, GEP);
11247 }
11248
11249 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011250 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011251 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011252 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011253 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011254 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011255 if (cast<GEPOperator>(&GEP)->isInBounds())
11256 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
Reid Spencer3da59db2006-11-27 01:05:10 +000011257 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11258 // The NewGEP must be pointer typed, so must the old one -> BitCast
11259 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011260 }
11261 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011262 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011263 }
Chris Lattner58407792009-01-09 04:53:57 +000011264
Chris Lattner46cd5a12009-01-09 05:44:56 +000011265 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011266 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011267 /// Y = gep X, <...constant indices...>
11268 /// into a gep of the original struct. This is important for SROA and alias
11269 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011270 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011271 if (TD &&
11272 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011273 // Determine how much the GEP moves the pointer. We are guaranteed to get
11274 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011275 ConstantInt *OffsetV =
11276 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011277 int64_t Offset = OffsetV->getSExtValue();
11278
11279 // If this GEP instruction doesn't move the pointer, just replace the GEP
11280 // with a bitcast of the real input to the dest type.
11281 if (Offset == 0) {
11282 // If the bitcast is of an allocation, and the allocation will be
11283 // converted to match the type of the cast, don't touch this.
11284 if (isa<AllocationInst>(BCI->getOperand(0))) {
11285 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11286 if (Instruction *I = visitBitCast(*BCI)) {
11287 if (I != BCI) {
11288 I->takeName(BCI);
11289 BCI->getParent()->getInstList().insert(BCI, I);
11290 ReplaceInstUsesWith(*BCI, I);
11291 }
11292 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011293 }
Chris Lattner58407792009-01-09 04:53:57 +000011294 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011295 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011296 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011297
11298 // Otherwise, if the offset is non-zero, we need to find out if there is a
11299 // field at Offset in 'A's type. If so, we can pull the cast through the
11300 // GEP.
11301 SmallVector<Value*, 8> NewIndices;
11302 const Type *InTy =
11303 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011304 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011305 Instruction *NGEP =
11306 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11307 NewIndices.end());
11308 if (NGEP->getType() == GEP.getType()) return NGEP;
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011309 if (cast<GEPOperator>(&GEP)->isInBounds())
11310 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011311 InsertNewInstBefore(NGEP, GEP);
11312 NGEP->takeName(&GEP);
11313 return new BitCastInst(NGEP, GEP.getType());
11314 }
Chris Lattner58407792009-01-09 04:53:57 +000011315 }
11316 }
11317
Chris Lattner8a2a3112001-12-14 16:52:21 +000011318 return 0;
11319}
11320
Chris Lattner0864acf2002-11-04 16:18:53 +000011321Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11322 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011323 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011324 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11325 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011326 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011327 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011328
11329 // Create and insert the replacement instruction...
11330 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +000011331 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011332 else {
11333 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Owen Anderson50dead02009-07-15 23:53:25 +000011334 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011335 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011336
11337 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011338
Chris Lattner0864acf2002-11-04 16:18:53 +000011339 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011340 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011341 //
11342 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011343 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011344
11345 // Now that I is pointing to the first non-allocation-inst in the block,
11346 // insert our getelementptr instruction...
11347 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011348 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011349 Value *Idx[2];
11350 Idx[0] = NullIdx;
11351 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011352 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11353 New->getName()+".sub", It);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011354 cast<GEPOperator>(V)->setIsInBounds(true);
Chris Lattner0864acf2002-11-04 16:18:53 +000011355
11356 // Now make everything use the getelementptr instead of the original
11357 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011358 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011359 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011360 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011361 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011362 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011363
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011364 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011365 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011366 // Note that we only do this for alloca's, because malloc should allocate
11367 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011368 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011369 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011370
11371 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11372 if (AI.getAlignment() == 0)
11373 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11374 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011375
Chris Lattner0864acf2002-11-04 16:18:53 +000011376 return 0;
11377}
11378
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011379Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11380 Value *Op = FI.getOperand(0);
11381
Chris Lattner17be6352004-10-18 02:59:09 +000011382 // free undef -> unreachable.
11383 if (isa<UndefValue>(Op)) {
11384 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011385 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +000011386 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011387 return EraseInstFromFunction(FI);
11388 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011389
Chris Lattner6160e852004-02-28 04:57:37 +000011390 // If we have 'free null' delete the instruction. This can happen in stl code
11391 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011392 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011393 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011394
11395 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11396 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11397 FI.setOperand(0, CI->getOperand(0));
11398 return &FI;
11399 }
11400
11401 // Change free (gep X, 0,0,0,0) into free(X)
11402 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11403 if (GEPI->hasAllZeroIndices()) {
11404 AddToWorkList(GEPI);
11405 FI.setOperand(0, GEPI->getOperand(0));
11406 return &FI;
11407 }
11408 }
11409
11410 // Change free(malloc) into nothing, if the malloc has a single use.
11411 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11412 if (MI->hasOneUse()) {
11413 EraseInstFromFunction(FI);
11414 return EraseInstFromFunction(*MI);
11415 }
Chris Lattner6160e852004-02-28 04:57:37 +000011416
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011417 return 0;
11418}
11419
11420
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011421/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011422static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011423 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011424 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011425 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011426 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011427
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011428 if (TD) {
11429 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11430 // Instead of loading constant c string, use corresponding integer value
11431 // directly if string length is small enough.
11432 std::string Str;
11433 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11434 unsigned len = Str.length();
11435 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11436 unsigned numBits = Ty->getPrimitiveSizeInBits();
11437 // Replace LI with immediate integer store.
11438 if ((numBits >> 3) == len + 1) {
11439 APInt StrVal(numBits, 0);
11440 APInt SingleChar(numBits, 0);
11441 if (TD->isLittleEndian()) {
11442 for (signed i = len-1; i >= 0; i--) {
11443 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11444 StrVal = (StrVal << 8) | SingleChar;
11445 }
11446 } else {
11447 for (unsigned i = 0; i < len; i++) {
11448 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11449 StrVal = (StrVal << 8) | SingleChar;
11450 }
11451 // Append NULL at the end.
11452 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011453 StrVal = (StrVal << 8) | SingleChar;
11454 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011455 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011456 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011457 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011458 }
11459 }
11460 }
11461
Mon P Wang6753f952009-02-07 22:19:29 +000011462 const PointerType *DestTy = cast<PointerType>(CI->getType());
11463 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011464 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011465
11466 // If the address spaces don't match, don't eliminate the cast.
11467 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11468 return 0;
11469
Chris Lattnerb89e0712004-07-13 01:49:43 +000011470 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011471
Reid Spencer42230162007-01-22 05:51:25 +000011472 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011473 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011474 // If the source is an array, the code below will not succeed. Check to
11475 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11476 // constants.
11477 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11478 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11479 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011480 Value *Idxs[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011481 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +000011482 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011483 SrcTy = cast<PointerType>(CastOp->getType());
11484 SrcPTy = SrcTy->getElementType();
11485 }
11486
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011487 if (IC.getTargetData() &&
11488 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011489 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011490 // Do not allow turning this into a load of an integer, which is then
11491 // casted to a pointer, this pessimizes pointer analysis a lot.
11492 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011493 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11494 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011495
Chris Lattnerf9527852005-01-31 04:50:46 +000011496 // Okay, we are casting from one integer or pointer type to another of
11497 // the same size. Instead of casting the pointer before the load, cast
11498 // the result of the loaded value.
11499 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11500 CI->getName(),
11501 LI.isVolatile()),LI);
11502 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011503 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011504 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011505 }
11506 }
11507 return 0;
11508}
11509
Chris Lattner833b8a42003-06-26 05:06:25 +000011510Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11511 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011512
Dan Gohman9941f742007-07-20 16:34:21 +000011513 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011514 if (TD) {
11515 unsigned KnownAlign =
11516 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11517 if (KnownAlign >
11518 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11519 LI.getAlignment()))
11520 LI.setAlignment(KnownAlign);
11521 }
Dan Gohman9941f742007-07-20 16:34:21 +000011522
Chris Lattner37366c12005-05-01 04:24:53 +000011523 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011524 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011525 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011526 return Res;
11527
11528 // None of the following transforms are legal for volatile loads.
11529 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011530
Dan Gohman2276a7b2008-10-15 23:19:35 +000011531 // Do really simple store-to-load forwarding and load CSE, to catch cases
11532 // where there are several consequtive memory accesses to the same location,
11533 // separated by a few arithmetic operations.
11534 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011535 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11536 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011537
Christopher Lambb15147e2007-12-29 07:56:53 +000011538 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11539 const Value *GEPI0 = GEPI->getOperand(0);
11540 // TODO: Consider a target hook for valid address spaces for this xform.
11541 if (isa<ConstantPointerNull>(GEPI0) &&
11542 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011543 // Insert a new store to null instruction before the load to indicate
11544 // that this code is not reachable. We do this instead of inserting
11545 // an unreachable instruction directly because we cannot modify the
11546 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011547 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011548 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011549 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011550 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011551 }
Chris Lattner37366c12005-05-01 04:24:53 +000011552
Chris Lattnere87597f2004-10-16 18:11:37 +000011553 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011554 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011555 // TODO: Consider a target hook for valid address spaces for this xform.
11556 if (isa<UndefValue>(C) || (C->isNullValue() &&
11557 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011558 // Insert a new store to null instruction before the load to indicate that
11559 // this code is not reachable. We do this instead of inserting an
11560 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011561 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011562 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011563 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011564 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011565
Chris Lattnere87597f2004-10-16 18:11:37 +000011566 // Instcombine load (constant global) into the value loaded.
11567 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011568 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011569 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011570
Chris Lattnere87597f2004-10-16 18:11:37 +000011571 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011572 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011573 if (CE->getOpcode() == Instruction::GetElementPtr) {
11574 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011575 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011576 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011577 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Andersone922c022009-07-22 00:24:57 +000011578 *Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011579 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011580 if (CE->getOperand(0)->isNullValue()) {
11581 // Insert a new store to null instruction before the load to indicate
11582 // that this code is not reachable. We do this instead of inserting
11583 // an unreachable instruction directly because we cannot modify the
11584 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011585 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011586 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011587 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011588 }
11589
Reid Spencer3da59db2006-11-27 01:05:10 +000011590 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011591 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011592 return Res;
11593 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011594 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011595 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011596
11597 // If this load comes from anywhere in a constant global, and if the global
11598 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011599 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011600 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011601 if (GV->getInitializer()->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +000011602 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011603 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011604 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011605 }
11606 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011607
Chris Lattner37366c12005-05-01 04:24:53 +000011608 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011609 // Change select and PHI nodes to select values instead of addresses: this
11610 // helps alias analysis out a lot, allows many others simplifications, and
11611 // exposes redundancy in the code.
11612 //
11613 // Note that we cannot do the transformation unless we know that the
11614 // introduced loads cannot trap! Something like this is valid as long as
11615 // the condition is always false: load (select bool %C, int* null, int* %G),
11616 // but it would not be valid if we transformed it to load from null
11617 // unconditionally.
11618 //
11619 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11620 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011621 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11622 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011623 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011624 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011625 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011626 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011627 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011628 }
11629
Chris Lattner684fe212004-09-23 15:46:00 +000011630 // load (select (cond, null, P)) -> load P
11631 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11632 if (C->isNullValue()) {
11633 LI.setOperand(0, SI->getOperand(2));
11634 return &LI;
11635 }
11636
11637 // load (select (cond, P, null)) -> load P
11638 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11639 if (C->isNullValue()) {
11640 LI.setOperand(0, SI->getOperand(1));
11641 return &LI;
11642 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011643 }
11644 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011645 return 0;
11646}
11647
Reid Spencer55af2b52007-01-19 21:20:31 +000011648/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011649/// when possible. This makes it generally easy to do alias analysis and/or
11650/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011651static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11652 User *CI = cast<User>(SI.getOperand(1));
11653 Value *CastOp = CI->getOperand(0);
11654
11655 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011656 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11657 if (SrcTy == 0) return 0;
11658
11659 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011660
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011661 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11662 return 0;
11663
Chris Lattner3914f722009-01-24 01:00:13 +000011664 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11665 /// to its first element. This allows us to handle things like:
11666 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11667 /// on 32-bit hosts.
11668 SmallVector<Value*, 4> NewGEPIndices;
11669
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011670 // If the source is an array, the code below will not succeed. Check to
11671 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11672 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011673 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11674 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011675 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011676 NewGEPIndices.push_back(Zero);
11677
11678 while (1) {
11679 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011680 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011681 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011682 NewGEPIndices.push_back(Zero);
11683 SrcPTy = STy->getElementType(0);
11684 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11685 NewGEPIndices.push_back(Zero);
11686 SrcPTy = ATy->getElementType();
11687 } else {
11688 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011689 }
Chris Lattner3914f722009-01-24 01:00:13 +000011690 }
11691
Owen Andersondebcb012009-07-29 22:17:13 +000011692 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011693 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011694
11695 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11696 return 0;
11697
Chris Lattner71759c42009-01-16 20:12:52 +000011698 // If the pointers point into different address spaces or if they point to
11699 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011700 if (!IC.getTargetData() ||
11701 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011702 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011703 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11704 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011705 return 0;
11706
11707 // Okay, we are casting from one integer or pointer type to another of
11708 // the same size. Instead of casting the pointer before
11709 // the store, cast the value to be stored.
11710 Value *NewCast;
11711 Value *SIOp0 = SI.getOperand(0);
11712 Instruction::CastOps opcode = Instruction::BitCast;
11713 const Type* CastSrcTy = SIOp0->getType();
11714 const Type* CastDstTy = SrcPTy;
11715 if (isa<PointerType>(CastDstTy)) {
11716 if (CastSrcTy->isInteger())
11717 opcode = Instruction::IntToPtr;
11718 } else if (isa<IntegerType>(CastDstTy)) {
11719 if (isa<PointerType>(SIOp0->getType()))
11720 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011721 }
Chris Lattner3914f722009-01-24 01:00:13 +000011722
11723 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11724 // emit a GEP to index into its first field.
11725 if (!NewGEPIndices.empty()) {
11726 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Andersonbaf3c402009-07-29 18:55:55 +000011727 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner3914f722009-01-24 01:00:13 +000011728 NewGEPIndices.size());
11729 else
11730 CastOp = IC.InsertNewInstBefore(
11731 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11732 NewGEPIndices.end()), SI);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011733 cast<GEPOperator>(CastOp)->setIsInBounds(true);
Chris Lattner3914f722009-01-24 01:00:13 +000011734 }
11735
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011736 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Andersonbaf3c402009-07-29 18:55:55 +000011737 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011738 else
11739 NewCast = IC.InsertNewInstBefore(
11740 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11741 SI);
11742 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011743}
11744
Chris Lattner4aebaee2008-11-27 08:56:30 +000011745/// equivalentAddressValues - Test if A and B will obviously have the same
11746/// value. This includes recognizing that %t0 and %t1 will have the same
11747/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011748/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011749/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011750/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011751/// %t2 = load i32* %t1
11752///
11753static bool equivalentAddressValues(Value *A, Value *B) {
11754 // Test if the values are trivially equivalent.
11755 if (A == B) return true;
11756
11757 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011758 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11759 // its only used to compare two uses within the same basic block, which
11760 // means that they'll always either have the same value or one of them
11761 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011762 if (isa<BinaryOperator>(A) ||
11763 isa<CastInst>(A) ||
11764 isa<PHINode>(A) ||
11765 isa<GetElementPtrInst>(A))
11766 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011767 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011768 return true;
11769
11770 // Otherwise they may not be equivalent.
11771 return false;
11772}
11773
Dale Johannesen4945c652009-03-03 21:26:39 +000011774// If this instruction has two uses, one of which is a llvm.dbg.declare,
11775// return the llvm.dbg.declare.
11776DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11777 if (!V->hasNUses(2))
11778 return 0;
11779 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11780 UI != E; ++UI) {
11781 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11782 return DI;
11783 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11784 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11785 return DI;
11786 }
11787 }
11788 return 0;
11789}
11790
Chris Lattner2f503e62005-01-31 05:36:43 +000011791Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11792 Value *Val = SI.getOperand(0);
11793 Value *Ptr = SI.getOperand(1);
11794
11795 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011796 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011797 ++NumCombined;
11798 return 0;
11799 }
Chris Lattner836692d2007-01-15 06:51:56 +000011800
11801 // If the RHS is an alloca with a single use, zapify the store, making the
11802 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011803 // If the RHS is an alloca with a two uses, the other one being a
11804 // llvm.dbg.declare, zapify the store and the declare, making the
11805 // alloca dead. We must do this to prevent declare's from affecting
11806 // codegen.
11807 if (!SI.isVolatile()) {
11808 if (Ptr->hasOneUse()) {
11809 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011810 EraseInstFromFunction(SI);
11811 ++NumCombined;
11812 return 0;
11813 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011814 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11815 if (isa<AllocaInst>(GEP->getOperand(0))) {
11816 if (GEP->getOperand(0)->hasOneUse()) {
11817 EraseInstFromFunction(SI);
11818 ++NumCombined;
11819 return 0;
11820 }
11821 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11822 EraseInstFromFunction(*DI);
11823 EraseInstFromFunction(SI);
11824 ++NumCombined;
11825 return 0;
11826 }
11827 }
11828 }
11829 }
11830 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11831 EraseInstFromFunction(*DI);
11832 EraseInstFromFunction(SI);
11833 ++NumCombined;
11834 return 0;
11835 }
Chris Lattner836692d2007-01-15 06:51:56 +000011836 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011837
Dan Gohman9941f742007-07-20 16:34:21 +000011838 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011839 if (TD) {
11840 unsigned KnownAlign =
11841 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11842 if (KnownAlign >
11843 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11844 SI.getAlignment()))
11845 SI.setAlignment(KnownAlign);
11846 }
Dan Gohman9941f742007-07-20 16:34:21 +000011847
Dale Johannesenacb51a32009-03-03 01:43:03 +000011848 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011849 // stores to the same location, separated by a few arithmetic operations. This
11850 // situation often occurs with bitfield accesses.
11851 BasicBlock::iterator BBI = &SI;
11852 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11853 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011854 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011855 // Don't count debug info directives, lest they affect codegen,
11856 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11857 // It is necessary for correctness to skip those that feed into a
11858 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011859 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011860 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011861 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011862 continue;
11863 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011864
11865 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11866 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011867 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11868 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011869 ++NumDeadStore;
11870 ++BBI;
11871 EraseInstFromFunction(*PrevSI);
11872 continue;
11873 }
11874 break;
11875 }
11876
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011877 // If this is a load, we have to stop. However, if the loaded value is from
11878 // the pointer we're loading and is producing the pointer we're storing,
11879 // then *this* store is dead (X = load P; store X -> P).
11880 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011881 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11882 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011883 EraseInstFromFunction(SI);
11884 ++NumCombined;
11885 return 0;
11886 }
11887 // Otherwise, this is a load from some other location. Stores before it
11888 // may not be dead.
11889 break;
11890 }
11891
Chris Lattner9ca96412006-02-08 03:25:32 +000011892 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011893 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011894 break;
11895 }
11896
11897
11898 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011899
11900 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011901 if (isa<ConstantPointerNull>(Ptr) &&
11902 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011903 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011904 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011905 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011906 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011907 ++NumCombined;
11908 }
11909 return 0; // Do not modify these!
11910 }
11911
11912 // store undef, Ptr -> noop
11913 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011914 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011915 ++NumCombined;
11916 return 0;
11917 }
11918
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011919 // If the pointer destination is a cast, see if we can fold the cast into the
11920 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011921 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011922 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11923 return Res;
11924 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011925 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011926 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11927 return Res;
11928
Chris Lattner408902b2005-09-12 23:23:25 +000011929
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011930 // If this store is the last instruction in the basic block (possibly
11931 // excepting debug info instructions and the pointer bitcasts that feed
11932 // into them), and if the block ends with an unconditional branch, try
11933 // to move it to the successor block.
11934 BBI = &SI;
11935 do {
11936 ++BBI;
11937 } while (isa<DbgInfoIntrinsic>(BBI) ||
11938 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011939 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011940 if (BI->isUnconditional())
11941 if (SimplifyStoreAtEndOfBlock(SI))
11942 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011943
Chris Lattner2f503e62005-01-31 05:36:43 +000011944 return 0;
11945}
11946
Chris Lattner3284d1f2007-04-15 00:07:55 +000011947/// SimplifyStoreAtEndOfBlock - Turn things like:
11948/// if () { *P = v1; } else { *P = v2 }
11949/// into a phi node with a store in the successor.
11950///
Chris Lattner31755a02007-04-15 01:02:18 +000011951/// Simplify things like:
11952/// *P = v1; if () { *P = v2; }
11953/// into a phi node with a store in the successor.
11954///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011955bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11956 BasicBlock *StoreBB = SI.getParent();
11957
11958 // Check to see if the successor block has exactly two incoming edges. If
11959 // so, see if the other predecessor contains a store to the same location.
11960 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011961 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011962
11963 // Determine whether Dest has exactly two predecessors and, if so, compute
11964 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011965 pred_iterator PI = pred_begin(DestBB);
11966 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011967 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011968 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011969 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011970 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011971 return false;
11972
11973 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011974 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011975 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011976 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011977 }
Chris Lattner31755a02007-04-15 01:02:18 +000011978 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011979 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011980
11981 // Bail out if all the relevant blocks aren't distinct (this can happen,
11982 // for example, if SI is in an infinite loop)
11983 if (StoreBB == DestBB || OtherBB == DestBB)
11984 return false;
11985
Chris Lattner31755a02007-04-15 01:02:18 +000011986 // Verify that the other block ends in a branch and is not otherwise empty.
11987 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011988 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011989 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011990 return false;
11991
Chris Lattner31755a02007-04-15 01:02:18 +000011992 // If the other block ends in an unconditional branch, check for the 'if then
11993 // else' case. there is an instruction before the branch.
11994 StoreInst *OtherStore = 0;
11995 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011996 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011997 // Skip over debugging info.
11998 while (isa<DbgInfoIntrinsic>(BBI) ||
11999 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12000 if (BBI==OtherBB->begin())
12001 return false;
12002 --BBI;
12003 }
12004 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012005 OtherStore = dyn_cast<StoreInst>(BBI);
12006 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12007 return false;
12008 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012009 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012010 // destinations is StoreBB, then we have the if/then case.
12011 if (OtherBr->getSuccessor(0) != StoreBB &&
12012 OtherBr->getSuccessor(1) != StoreBB)
12013 return false;
12014
12015 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012016 // if/then triangle. See if there is a store to the same ptr as SI that
12017 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012018 for (;; --BBI) {
12019 // Check to see if we find the matching store.
12020 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12021 if (OtherStore->getOperand(1) != SI.getOperand(1))
12022 return false;
12023 break;
12024 }
Eli Friedman6903a242008-06-13 22:02:12 +000012025 // If we find something that may be using or overwriting the stored
12026 // value, or if we run out of instructions, we can't do the xform.
12027 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012028 BBI == OtherBB->begin())
12029 return false;
12030 }
12031
12032 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012033 // make sure nothing reads or overwrites the stored value in
12034 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012035 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12036 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012037 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012038 return false;
12039 }
12040 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012041
Chris Lattner31755a02007-04-15 01:02:18 +000012042 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012043 Value *MergedVal = OtherStore->getOperand(0);
12044 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012045 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012046 PN->reserveOperandSpace(2);
12047 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012048 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12049 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012050 }
12051
12052 // Advance to a place where it is safe to insert the new store and
12053 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012054 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012055 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12056 OtherStore->isVolatile()), *BBI);
12057
12058 // Nuke the old stores.
12059 EraseInstFromFunction(SI);
12060 EraseInstFromFunction(*OtherStore);
12061 ++NumCombined;
12062 return true;
12063}
12064
Chris Lattner2f503e62005-01-31 05:36:43 +000012065
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012066Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12067 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012068 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012069 BasicBlock *TrueDest;
12070 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000012071 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012072 !isa<Constant>(X)) {
12073 // Swap Destinations and condition...
12074 BI.setCondition(X);
12075 BI.setSuccessor(0, FalseDest);
12076 BI.setSuccessor(1, TrueDest);
12077 return &BI;
12078 }
12079
Reid Spencere4d87aa2006-12-23 06:05:41 +000012080 // Cannonicalize fcmp_one -> fcmp_oeq
12081 FCmpInst::Predicate FPred; Value *Y;
12082 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Dan Gohman4ae51262009-08-12 16:23:25 +000012083 TrueDest, FalseDest)))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012084 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12085 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12086 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012087 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012088 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012089 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012090 // Swap Destinations and condition...
12091 BI.setCondition(NewSCC);
12092 BI.setSuccessor(0, FalseDest);
12093 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012094 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012095 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012096 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012097 return &BI;
12098 }
12099
12100 // Cannonicalize icmp_ne -> icmp_eq
12101 ICmpInst::Predicate IPred;
12102 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Dan Gohman4ae51262009-08-12 16:23:25 +000012103 TrueDest, FalseDest)))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012104 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12105 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12106 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12107 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012108 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012109 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012110 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000012111 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012112 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012113 BI.setSuccessor(0, FalseDest);
12114 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012115 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012116 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012117 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012118 return &BI;
12119 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012120
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012121 return 0;
12122}
Chris Lattner0864acf2002-11-04 16:18:53 +000012123
Chris Lattner46238a62004-07-03 00:26:11 +000012124Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12125 Value *Cond = SI.getCondition();
12126 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12127 if (I->getOpcode() == Instruction::Add)
12128 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12129 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12130 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012131 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012132 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012133 AddRHS));
12134 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000012135 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012136 return &SI;
12137 }
12138 }
12139 return 0;
12140}
12141
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012142Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012143 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012144
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012145 if (!EV.hasIndices())
12146 return ReplaceInstUsesWith(EV, Agg);
12147
12148 if (Constant *C = dyn_cast<Constant>(Agg)) {
12149 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012150 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012151
12152 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012153 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012154
12155 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12156 // Extract the element indexed by the first index out of the constant
12157 Value *V = C->getOperand(*EV.idx_begin());
12158 if (EV.getNumIndices() > 1)
12159 // Extract the remaining indices out of the constant indexed by the
12160 // first index
12161 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12162 else
12163 return ReplaceInstUsesWith(EV, V);
12164 }
12165 return 0; // Can't handle other constants
12166 }
12167 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12168 // We're extracting from an insertvalue instruction, compare the indices
12169 const unsigned *exti, *exte, *insi, *inse;
12170 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12171 exte = EV.idx_end(), inse = IV->idx_end();
12172 exti != exte && insi != inse;
12173 ++exti, ++insi) {
12174 if (*insi != *exti)
12175 // The insert and extract both reference distinctly different elements.
12176 // This means the extract is not influenced by the insert, and we can
12177 // replace the aggregate operand of the extract with the aggregate
12178 // operand of the insert. i.e., replace
12179 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12180 // %E = extractvalue { i32, { i32 } } %I, 0
12181 // with
12182 // %E = extractvalue { i32, { i32 } } %A, 0
12183 return ExtractValueInst::Create(IV->getAggregateOperand(),
12184 EV.idx_begin(), EV.idx_end());
12185 }
12186 if (exti == exte && insi == inse)
12187 // Both iterators are at the end: Index lists are identical. Replace
12188 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12189 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12190 // with "i32 42"
12191 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12192 if (exti == exte) {
12193 // The extract list is a prefix of the insert list. i.e. replace
12194 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12195 // %E = extractvalue { i32, { i32 } } %I, 1
12196 // with
12197 // %X = extractvalue { i32, { i32 } } %A, 1
12198 // %E = insertvalue { i32 } %X, i32 42, 0
12199 // by switching the order of the insert and extract (though the
12200 // insertvalue should be left in, since it may have other uses).
12201 Value *NewEV = InsertNewInstBefore(
12202 ExtractValueInst::Create(IV->getAggregateOperand(),
12203 EV.idx_begin(), EV.idx_end()),
12204 EV);
12205 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12206 insi, inse);
12207 }
12208 if (insi == inse)
12209 // The insert list is a prefix of the extract list
12210 // We can simply remove the common indices from the extract and make it
12211 // operate on the inserted value instead of the insertvalue result.
12212 // i.e., replace
12213 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12214 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12215 // with
12216 // %E extractvalue { i32 } { i32 42 }, 0
12217 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12218 exti, exte);
12219 }
12220 // Can't simplify extracts from other values. Note that nested extracts are
12221 // already simplified implicitely by the above (extract ( extract (insert) )
12222 // will be translated into extract ( insert ( extract ) ) first and then just
12223 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012224 return 0;
12225}
12226
Chris Lattner220b0cf2006-03-05 00:22:33 +000012227/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12228/// is to leave as a vector operation.
12229static bool CheapToScalarize(Value *V, bool isConstant) {
12230 if (isa<ConstantAggregateZero>(V))
12231 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012232 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012233 if (isConstant) return true;
12234 // If all elts are the same, we can extract.
12235 Constant *Op0 = C->getOperand(0);
12236 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12237 if (C->getOperand(i) != Op0)
12238 return false;
12239 return true;
12240 }
12241 Instruction *I = dyn_cast<Instruction>(V);
12242 if (!I) return false;
12243
12244 // Insert element gets simplified to the inserted element or is deleted if
12245 // this is constant idx extract element and its a constant idx insertelt.
12246 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12247 isa<ConstantInt>(I->getOperand(2)))
12248 return true;
12249 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12250 return true;
12251 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12252 if (BO->hasOneUse() &&
12253 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12254 CheapToScalarize(BO->getOperand(1), isConstant)))
12255 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012256 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12257 if (CI->hasOneUse() &&
12258 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12259 CheapToScalarize(CI->getOperand(1), isConstant)))
12260 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012261
12262 return false;
12263}
12264
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012265/// Read and decode a shufflevector mask.
12266///
12267/// It turns undef elements into values that are larger than the number of
12268/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012269static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12270 unsigned NElts = SVI->getType()->getNumElements();
12271 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12272 return std::vector<unsigned>(NElts, 0);
12273 if (isa<UndefValue>(SVI->getOperand(2)))
12274 return std::vector<unsigned>(NElts, 2*NElts);
12275
12276 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012277 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012278 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12279 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012280 Result.push_back(NElts*2); // undef -> 8
12281 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012282 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012283 return Result;
12284}
12285
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012286/// FindScalarElement - Given a vector and an element number, see if the scalar
12287/// value is already around as a register, for example if it were inserted then
12288/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012289static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012290 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012291 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12292 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012293 unsigned Width = PTy->getNumElements();
12294 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012295 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012296
12297 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012298 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012299 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012300 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012301 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012302 return CP->getOperand(EltNo);
12303 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12304 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012305 if (!isa<ConstantInt>(III->getOperand(2)))
12306 return 0;
12307 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012308
12309 // If this is an insert to the element we are looking for, return the
12310 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012311 if (EltNo == IIElt)
12312 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012313
12314 // Otherwise, the insertelement doesn't modify the value, recurse on its
12315 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012316 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012317 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012318 unsigned LHSWidth =
12319 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012320 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012321 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012322 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012323 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012324 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012325 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012326 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012327 }
12328
12329 // Otherwise, we don't know.
12330 return 0;
12331}
12332
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012333Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012334 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012335 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012336 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012337
Dan Gohman07a96762007-07-16 14:29:03 +000012338 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012339 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012340 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012341
Reid Spencer9d6565a2007-02-15 02:26:10 +000012342 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012343 // If vector val is constant with all elements the same, replace EI with
12344 // that element. When the elements are not identical, we cannot replace yet
12345 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012346 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012347 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012348 if (C->getOperand(i) != op0) {
12349 op0 = 0;
12350 break;
12351 }
12352 if (op0)
12353 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012354 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012355
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012356 // If extracting a specified index from the vector, see if we can recursively
12357 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012358 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012359 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedman76e7ba82009-07-18 19:04:16 +000012360 unsigned VectorWidth =
12361 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012362
12363 // If this is extracting an invalid index, turn this into undef, to avoid
12364 // crashing the code below.
12365 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012366 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012367
Chris Lattner867b99f2006-10-05 06:55:50 +000012368 // This instruction only demands the single element from the input vector.
12369 // If the input vector has a single use, simplify it based on this use
12370 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012371 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012372 APInt UndefElts(VectorWidth, 0);
12373 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012374 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012375 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012376 EI.setOperand(0, V);
12377 return &EI;
12378 }
12379 }
12380
Owen Andersond672ecb2009-07-03 00:17:18 +000012381 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012382 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012383
12384 // If the this extractelement is directly using a bitcast from a vector of
12385 // the same number of elements, see if we can find the source element from
12386 // it. In this case, we will end up needing to bitcast the scalars.
12387 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12388 if (const VectorType *VT =
12389 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12390 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012391 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12392 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012393 return new BitCastInst(Elt, EI.getType());
12394 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012395 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012396
Chris Lattner73fa49d2006-05-25 22:53:38 +000012397 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012398 if (I->hasOneUse()) {
12399 // Push extractelement into predecessor operation if legal and
12400 // profitable to do so
12401 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012402 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12403 if (CheapToScalarize(BO, isConstantElt)) {
12404 ExtractElementInst *newEI0 =
Eric Christophera3500da2009-07-25 02:28:41 +000012405 ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
Chris Lattner220b0cf2006-03-05 00:22:33 +000012406 EI.getName()+".lhs");
12407 ExtractElementInst *newEI1 =
Eric Christophera3500da2009-07-25 02:28:41 +000012408 ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
Chris Lattner220b0cf2006-03-05 00:22:33 +000012409 EI.getName()+".rhs");
12410 InsertNewInstBefore(newEI0, EI);
12411 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012412 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012413 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012414 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012415 unsigned AS =
12416 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012417 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Mon P Wang7c4efa62009-08-13 05:12:13 +000012418 PointerType::get(EI.getType(), AS),*I);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012419 GetElementPtrInst *GEP =
12420 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmand6aa02d2009-07-28 01:40:03 +000012421 cast<GEPOperator>(GEP)->setIsInBounds(true);
Mon P Wang7c4efa62009-08-13 05:12:13 +000012422 InsertNewInstBefore(GEP, *I);
12423 LoadInst* Load = new LoadInst(GEP, "tmp");
12424 InsertNewInstBefore(Load, *I);
12425 return ReplaceInstUsesWith(EI, Load);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012426 }
12427 }
12428 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12429 // Extracting the inserted element?
12430 if (IE->getOperand(2) == EI.getOperand(1))
12431 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12432 // If the inserted and extracted elements are constants, they must not
12433 // be the same value, extract from the pre-inserted value instead.
12434 if (isa<Constant>(IE->getOperand(2)) &&
12435 isa<Constant>(EI.getOperand(1))) {
12436 AddUsesToWorkList(EI);
12437 EI.setOperand(0, IE->getOperand(0));
12438 return &EI;
12439 }
12440 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12441 // If this is extracting an element from a shufflevector, figure out where
12442 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012443 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12444 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012445 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012446 unsigned LHSWidth =
12447 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12448
12449 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012450 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012451 else if (SrcIdx < LHSWidth*2) {
12452 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012453 Src = SVI->getOperand(1);
12454 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012455 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012456 }
Eric Christophera3500da2009-07-25 02:28:41 +000012457 return ExtractElementInst::Create(Src,
Owen Anderson1d0be152009-08-13 21:58:54 +000012458 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012459 }
12460 }
Eli Friedman2451a642009-07-18 23:06:53 +000012461 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012462 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012463 return 0;
12464}
12465
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012466/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12467/// elements from either LHS or RHS, return the shuffle mask and true.
12468/// Otherwise, return false.
12469static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012470 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012471 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012472 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12473 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012474 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012475
12476 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012477 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012478 return true;
12479 } else if (V == LHS) {
12480 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012481 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012482 return true;
12483 } else if (V == RHS) {
12484 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012485 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012486 return true;
12487 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12488 // If this is an insert of an extract from some other vector, include it.
12489 Value *VecOp = IEI->getOperand(0);
12490 Value *ScalarOp = IEI->getOperand(1);
12491 Value *IdxOp = IEI->getOperand(2);
12492
Chris Lattnerd929f062006-04-27 21:14:21 +000012493 if (!isa<ConstantInt>(IdxOp))
12494 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012495 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012496
12497 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12498 // Okay, we can handle this if the vector we are insertinting into is
12499 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012500 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012501 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012502 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012503 return true;
12504 }
12505 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12506 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012507 EI->getOperand(0)->getType() == V->getType()) {
12508 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012509 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012510
12511 // This must be extracting from either LHS or RHS.
12512 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12513 // Okay, we can handle this if the vector we are insertinting into is
12514 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012515 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012516 // If so, update the mask to reflect the inserted value.
12517 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012518 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012519 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012520 } else {
12521 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012522 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012523 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012524
12525 }
12526 return true;
12527 }
12528 }
12529 }
12530 }
12531 }
12532 // TODO: Handle shufflevector here!
12533
12534 return false;
12535}
12536
12537/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12538/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12539/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012540static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012541 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012542 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012543 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012544 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012545 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012546
12547 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012548 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012549 return V;
12550 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012551 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012552 return V;
12553 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12554 // If this is an insert of an extract from some other vector, include it.
12555 Value *VecOp = IEI->getOperand(0);
12556 Value *ScalarOp = IEI->getOperand(1);
12557 Value *IdxOp = IEI->getOperand(2);
12558
12559 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12560 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12561 EI->getOperand(0)->getType() == V->getType()) {
12562 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012563 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12564 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012565
12566 // Either the extracted from or inserted into vector must be RHSVec,
12567 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012568 if (EI->getOperand(0) == RHS || RHS == 0) {
12569 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012570 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012571 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012572 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012573 return V;
12574 }
12575
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012576 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012577 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12578 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012579 // Everything but the extracted element is replaced with the RHS.
12580 for (unsigned i = 0; i != NumElts; ++i) {
12581 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012582 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012583 }
12584 return V;
12585 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012586
12587 // If this insertelement is a chain that comes from exactly these two
12588 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012589 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12590 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012591 return EI->getOperand(0);
12592
Chris Lattnerefb47352006-04-15 01:39:45 +000012593 }
12594 }
12595 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012596 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012597
12598 // Otherwise, can't do anything fancy. Return an identity vector.
12599 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012600 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012601 return V;
12602}
12603
12604Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12605 Value *VecOp = IE.getOperand(0);
12606 Value *ScalarOp = IE.getOperand(1);
12607 Value *IdxOp = IE.getOperand(2);
12608
Chris Lattner599ded12007-04-09 01:11:16 +000012609 // Inserting an undef or into an undefined place, remove this.
12610 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12611 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012612
Chris Lattnerefb47352006-04-15 01:39:45 +000012613 // If the inserted element was extracted from some other vector, and if the
12614 // indexes are constant, try to turn this into a shufflevector operation.
12615 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12616 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12617 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012618 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012619 unsigned ExtractedIdx =
12620 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012621 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012622
12623 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12624 return ReplaceInstUsesWith(IE, VecOp);
12625
12626 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012627 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012628
12629 // If we are extracting a value from a vector, then inserting it right
12630 // back into the same place, just use the input vector.
12631 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12632 return ReplaceInstUsesWith(IE, VecOp);
12633
12634 // We could theoretically do this for ANY input. However, doing so could
12635 // turn chains of insertelement instructions into a chain of shufflevector
12636 // instructions, and right now we do not merge shufflevectors. As such,
12637 // only do this in a situation where it is clear that there is benefit.
12638 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12639 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12640 // the values of VecOp, except then one read from EIOp0.
12641 // Build a new shuffle mask.
12642 std::vector<Constant*> Mask;
12643 if (isa<UndefValue>(VecOp))
Owen Anderson1d0be152009-08-13 21:58:54 +000012644 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012645 else {
12646 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Anderson1d0be152009-08-13 21:58:54 +000012647 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
Chris Lattnerefb47352006-04-15 01:39:45 +000012648 NumVectorElts));
12649 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012650 Mask[InsertedIdx] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012651 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012652 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012653 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012654 }
12655
12656 // If this insertelement isn't used by some other insertelement, turn it
12657 // (and any insertelements it points to), into one big shuffle.
12658 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12659 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012660 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012661 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012662 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012663 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012664 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012665 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012666 }
12667 }
12668 }
12669
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012670 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12671 APInt UndefElts(VWidth, 0);
12672 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12673 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12674 return &IE;
12675
Chris Lattnerefb47352006-04-15 01:39:45 +000012676 return 0;
12677}
12678
12679
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012680Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12681 Value *LHS = SVI.getOperand(0);
12682 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012683 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012684
12685 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012686
Chris Lattner867b99f2006-10-05 06:55:50 +000012687 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012688 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012689 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012690
Dan Gohman488fbfc2008-09-09 18:11:14 +000012691 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012692
12693 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12694 return 0;
12695
Evan Cheng388df622009-02-03 10:05:09 +000012696 APInt UndefElts(VWidth, 0);
12697 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12698 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012699 LHS = SVI.getOperand(0);
12700 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012701 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012702 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012703
Chris Lattner863bcff2006-05-25 23:48:38 +000012704 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12705 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12706 if (LHS == RHS || isa<UndefValue>(LHS)) {
12707 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012708 // shuffle(undef,undef,mask) -> undef.
12709 return ReplaceInstUsesWith(SVI, LHS);
12710 }
12711
Chris Lattner863bcff2006-05-25 23:48:38 +000012712 // Remap any references to RHS to use LHS.
12713 std::vector<Constant*> Elts;
12714 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012715 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012716 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012717 else {
12718 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012719 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012720 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012721 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012722 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012723 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012724 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012725 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012726 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012727 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012728 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012729 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012730 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012731 LHS = SVI.getOperand(0);
12732 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012733 MadeChange = true;
12734 }
12735
Chris Lattner7b2e27922006-05-26 00:29:06 +000012736 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012737 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012738
Chris Lattner863bcff2006-05-25 23:48:38 +000012739 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12740 if (Mask[i] >= e*2) continue; // Ignore undef values.
12741 // Is this an identity shuffle of the LHS value?
12742 isLHSID &= (Mask[i] == i);
12743
12744 // Is this an identity shuffle of the RHS value?
12745 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012746 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012747
Chris Lattner863bcff2006-05-25 23:48:38 +000012748 // Eliminate identity shuffles.
12749 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12750 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012751
Chris Lattner7b2e27922006-05-26 00:29:06 +000012752 // If the LHS is a shufflevector itself, see if we can combine it with this
12753 // one without producing an unusual shuffle. Here we are really conservative:
12754 // we are absolutely afraid of producing a shuffle mask not in the input
12755 // program, because the code gen may not be smart enough to turn a merged
12756 // shuffle into two specific shuffles: it may produce worse code. As such,
12757 // we only merge two shuffles if the result is one of the two input shuffle
12758 // masks. In this case, merging the shuffles just removes one instruction,
12759 // which we know is safe. This is good for things like turning:
12760 // (splat(splat)) -> splat.
12761 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12762 if (isa<UndefValue>(RHS)) {
12763 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12764
12765 std::vector<unsigned> NewMask;
12766 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12767 if (Mask[i] >= 2*e)
12768 NewMask.push_back(2*e);
12769 else
12770 NewMask.push_back(LHSMask[Mask[i]]);
12771
12772 // If the result mask is equal to the src shuffle or this shuffle mask, do
12773 // the replacement.
12774 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012775 unsigned LHSInNElts =
12776 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012777 std::vector<Constant*> Elts;
12778 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012779 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012780 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012781 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012782 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012783 }
12784 }
12785 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12786 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012787 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012788 }
12789 }
12790 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012791
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012792 return MadeChange ? &SVI : 0;
12793}
12794
12795
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012796
Chris Lattnerea1c4542004-12-08 23:43:58 +000012797
12798/// TryToSinkInstruction - Try to move the specified instruction from its
12799/// current block into the beginning of DestBlock, which can only happen if it's
12800/// safe to move the instruction past all of the instructions between it and the
12801/// end of its block.
12802static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12803 assert(I->hasOneUse() && "Invariants didn't hold!");
12804
Chris Lattner108e9022005-10-27 17:13:11 +000012805 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012806 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012807 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012808
Chris Lattnerea1c4542004-12-08 23:43:58 +000012809 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012810 if (isa<AllocaInst>(I) && I->getParent() ==
12811 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012812 return false;
12813
Chris Lattner96a52a62004-12-09 07:14:34 +000012814 // We can only sink load instructions if there is nothing between the load and
12815 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012816 if (I->mayReadFromMemory()) {
12817 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012818 Scan != E; ++Scan)
12819 if (Scan->mayWriteToMemory())
12820 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012821 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012822
Dan Gohman02dea8b2008-05-23 21:05:58 +000012823 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012824
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012825 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012826 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012827 ++NumSunkInst;
12828 return true;
12829}
12830
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012831
12832/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12833/// all reachable code to the worklist.
12834///
12835/// This has a couple of tricks to make the code faster and more powerful. In
12836/// particular, we constant fold and DCE instructions as we go, to avoid adding
12837/// them to the worklist (this significantly speeds up instcombine on code where
12838/// many instructions are dead or constant). Additionally, if we find a branch
12839/// whose condition is a known constant, we only visit the reachable successors.
12840///
12841static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012842 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012843 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012844 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012845 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012846 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012847
Chris Lattner2c7718a2007-03-23 19:17:18 +000012848 while (!Worklist.empty()) {
12849 BB = Worklist.back();
12850 Worklist.pop_back();
12851
12852 // We have now visited this block! If we've already been here, ignore it.
12853 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012854
12855 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012856 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12857 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012858
Chris Lattner2c7718a2007-03-23 19:17:18 +000012859 // DCE instruction if trivially dead.
12860 if (isInstructionTriviallyDead(Inst)) {
12861 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012862 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012863 Inst->eraseFromParent();
12864 continue;
12865 }
12866
12867 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012868 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012869 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12870 << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012871 Inst->replaceAllUsesWith(C);
12872 ++NumConstProp;
12873 Inst->eraseFromParent();
12874 continue;
12875 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012876
Devang Patel7fe1dec2008-11-19 18:56:50 +000012877 // If there are two consecutive llvm.dbg.stoppoint calls then
12878 // it is likely that the optimizer deleted code in between these
12879 // two intrinsics.
12880 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12881 if (DBI_Next) {
12882 if (DBI_Prev
12883 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12884 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12885 IC.RemoveFromWorkList(DBI_Prev);
12886 DBI_Prev->eraseFromParent();
12887 }
12888 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012889 } else {
12890 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012891 }
12892
Chris Lattner2c7718a2007-03-23 19:17:18 +000012893 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012894 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012895
12896 // Recursively visit successors. If this is a branch or switch on a
12897 // constant, only visit the reachable successor.
12898 TerminatorInst *TI = BB->getTerminator();
12899 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12900 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12901 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012902 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012903 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012904 continue;
12905 }
12906 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12907 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12908 // See if this is an explicit destination.
12909 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12910 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012911 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012912 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012913 continue;
12914 }
12915
12916 // Otherwise it is the default destination.
12917 Worklist.push_back(SI->getSuccessor(0));
12918 continue;
12919 }
12920 }
12921
12922 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12923 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012924 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012925}
12926
Chris Lattnerec9c3582007-03-03 02:04:50 +000012927bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012928 bool Changed = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012929 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012930
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012931 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12932 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012933
Chris Lattnerb3d59702005-07-07 20:40:38 +000012934 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012935 // Do a depth-first traversal of the function, populate the worklist with
12936 // the reachable instructions. Ignore blocks that are not reachable. Keep
12937 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012938 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012939 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012940
Chris Lattnerb3d59702005-07-07 20:40:38 +000012941 // Do a quick scan over the function. If we find any blocks that are
12942 // unreachable, remove any instructions inside of them. This prevents
12943 // the instcombine code from having to deal with some bad special cases.
12944 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12945 if (!Visited.count(BB)) {
12946 Instruction *Term = BB->getTerminator();
12947 while (Term != BB->begin()) { // Remove instrs bottom-up
12948 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012949
Chris Lattnerbdff5482009-08-23 04:37:46 +000012950 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012951 // A debug intrinsic shouldn't force another iteration if we weren't
12952 // going to do one without it.
12953 if (!isa<DbgInfoIntrinsic>(I)) {
12954 ++NumDeadInst;
12955 Changed = true;
12956 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012957 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012958 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012959 I->eraseFromParent();
12960 }
12961 }
12962 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012963
Chris Lattner873ff012009-08-30 05:55:36 +000012964 while (!Worklist.isEmpty()) {
12965 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012966 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012967
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012968 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012969 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012970 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012971 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012972 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012973 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012974
Chris Lattnerbdff5482009-08-23 04:37:46 +000012975 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012976
12977 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012978 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012979 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012980 continue;
12981 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012982
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012983 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012984 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012985 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012986
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012987 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012988 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000012989 ReplaceInstUsesWith(*I, C);
12990
Chris Lattner62b14df2002-09-02 04:59:56 +000012991 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012992 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012993 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012994 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012995 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012996 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012997
Eli Friedmanfd2934f2009-07-15 22:13:34 +000012998 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012999 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000013000 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13001 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000013002 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13003 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000013004 if (NewC != CE) {
13005 i->set(NewC);
13006 Changed = true;
13007 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013008 }
13009
Chris Lattnerea1c4542004-12-08 23:43:58 +000013010 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013011 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013012 BasicBlock *BB = I->getParent();
13013 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13014 if (UserParent != BB) {
13015 bool UserIsSuccessor = false;
13016 // See if the user is one of our successors.
13017 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13018 if (*SI == UserParent) {
13019 UserIsSuccessor = true;
13020 break;
13021 }
13022
13023 // If the user is one of our immediate successors, and if that successor
13024 // only has us as a predecessors (we'd have to split the critical edge
13025 // otherwise), we can keep going.
13026 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13027 next(pred_begin(UserParent)) == pred_end(UserParent))
13028 // Okay, the CFG is simple enough, try to sink this instruction.
13029 Changed |= TryToSinkInstruction(I, UserParent);
13030 }
13031 }
13032
Chris Lattner8a2a3112001-12-14 16:52:21 +000013033 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000013034#ifndef NDEBUG
13035 std::string OrigI;
13036#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000013037 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000013038 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013039 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013040 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013041 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013042 DEBUG(errs() << "IC: Old = " << *I << '\n'
13043 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000013044
Chris Lattnerf523d062004-06-09 05:08:07 +000013045 // Everything uses the new instruction now.
13046 I->replaceAllUsesWith(Result);
13047
13048 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013049 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000013050 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013051
Chris Lattner6934a042007-02-11 01:23:03 +000013052 // Move the name to the new instruction first.
13053 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013054
13055 // Insert the new instruction into the basic block...
13056 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013057 BasicBlock::iterator InsertPos = I;
13058
13059 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13060 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13061 ++InsertPos;
13062
13063 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013064
Chris Lattner00d51312004-05-01 23:27:23 +000013065 // Make sure that we reprocess all operands now that we reduced their
13066 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013067 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000013068
Chris Lattnerf523d062004-06-09 05:08:07 +000013069 // Instructions can end up on the worklist more than once. Make sure
13070 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013071 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013072
13073 // Erase the old instruction.
13074 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000013075 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013076#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000013077 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13078 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000013079#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013080
Chris Lattner90ac28c2002-08-02 19:29:35 +000013081 // If the instruction was modified, it's possible that it is now dead.
13082 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013083 if (isInstructionTriviallyDead(I)) {
13084 // Make sure we process all operands now that we are reducing their
13085 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000013086 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000013087
Chris Lattner00d51312004-05-01 23:27:23 +000013088 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013089 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013090 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000013091 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000013092 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000013093 AddToWorkList(I);
13094 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013095 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013096 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013097 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013098 }
13099 }
13100
Chris Lattner873ff012009-08-30 05:55:36 +000013101 Worklist.Zap();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013102 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013103}
13104
Chris Lattnerec9c3582007-03-03 02:04:50 +000013105
13106bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013107 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013108 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000013109
Chris Lattnerec9c3582007-03-03 02:04:50 +000013110 bool EverMadeChange = false;
13111
13112 // Iterate while there is work to do.
13113 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013114 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013115 EverMadeChange = true;
13116 return EverMadeChange;
13117}
13118
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013119FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013120 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013121}