blob: 3254a7caa4e7d3ce43e37cd8c58114d9e0abd7c0 [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"
Chris Lattner79066fa2007-01-30 23:46:24 +000043#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner173234a2008-06-02 01:18:21 +000044#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000045#include "llvm/Target/TargetData.h"
46#include "llvm/Transforms/Utils/BasicBlockUtils.h"
47#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000048#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000049#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000050#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000051#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000052#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000053#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000054#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000055#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000056#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000057#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000058#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000059#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000060#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000061#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000062#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000063#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000064#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000065using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000066using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000067
Chris Lattner0e5f4992006-12-19 21:40:18 +000068STATISTIC(NumCombined , "Number of insts combined");
69STATISTIC(NumConstProp, "Number of constant folds");
70STATISTIC(NumDeadInst , "Number of dead inst eliminated");
71STATISTIC(NumDeadStore, "Number of dead stores eliminated");
72STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000073
Chris Lattner0e5f4992006-12-19 21:40:18 +000074namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000075 class VISIBILITY_HIDDEN InstCombiner
76 : public FunctionPass,
77 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000078 // Worklist of all of the instructions that need to be simplified.
Chris Lattner2806dff2008-08-15 04:03:01 +000079 SmallVector<Instruction*, 256> Worklist;
Chris Lattnerdbab3862007-03-02 21:28:56 +000080 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000081 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000082 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000083 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000084 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000085 InstCombiner() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000086
Owen Anderson07cf79e2009-07-06 23:00:19 +000087 LLVMContext *getContext() { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +000088
Chris Lattnerdbab3862007-03-02 21:28:56 +000089 /// AddToWorkList - Add the specified instruction to the worklist if it
90 /// isn't already in it.
91 void AddToWorkList(Instruction *I) {
Dan Gohman6b345ee2008-07-07 17:46:23 +000092 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerdbab3862007-03-02 21:28:56 +000093 Worklist.push_back(I);
94 }
95
96 // RemoveFromWorkList - remove I from the worklist if it exists.
97 void RemoveFromWorkList(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 *RemoveOneFromWorkList() {
108 Instruction *I = Worklist.back();
109 Worklist.pop_back();
110 WorklistMap.erase(I);
111 return I;
112 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000113
Chris Lattnerdbab3862007-03-02 21:28:56 +0000114
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000115 /// AddUsersToWorkList - When an instruction is simplified, add all users of
116 /// the instruction to the work lists because they might get more simplified
117 /// now.
118 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000119 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000120 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000121 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000122 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000123 }
124
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000125 /// AddUsesToWorkList - When an instruction is simplified, add operands to
126 /// the work lists because they might get more simplified now.
127 ///
128 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000129 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
130 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000131 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000132 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000133
134 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
135 /// dead. Add all of its operands to the worklist, turning them into
136 /// undef's to reduce the number of uses of those instructions.
137 ///
138 /// Return the specified operand before it is turned into an undef.
139 ///
140 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
141 Value *R = I.getOperand(op);
142
Gabor Greif177dd3f2008-06-12 21:37:33 +0000143 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
144 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000145 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000146 // Set the operand to undef to drop the use.
Owen Andersond672ecb2009-07-03 00:17:18 +0000147 *i = Context->getUndef(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000148 }
149
150 return R;
151 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000152
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000153 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000154 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000155
156 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000157
Chris Lattner97e52e42002-04-28 21:27:06 +0000158 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000159 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000160 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000161 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000162 }
163
Chris Lattner28977af2004-04-05 01:30:19 +0000164 TargetData &getTargetData() const { return *TD; }
165
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000166 // Visitation implementation - Implement instruction combining for different
167 // instruction types. The semantics are as follows:
168 // Return Value:
169 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000170 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000171 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000172 //
Chris Lattner7e708292002-06-25 16:13:24 +0000173 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000174 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000175 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000176 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000177 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000178 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000179 Instruction *visitURem(BinaryOperator &I);
180 Instruction *visitSRem(BinaryOperator &I);
181 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000182 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000183 Instruction *commonRemTransforms(BinaryOperator &I);
184 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000185 Instruction *commonDivTransforms(BinaryOperator &I);
186 Instruction *commonIDivTransforms(BinaryOperator &I);
187 Instruction *visitUDiv(BinaryOperator &I);
188 Instruction *visitSDiv(BinaryOperator &I);
189 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000190 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000191 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000192 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000193 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000194 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000195 Instruction *visitOr (BinaryOperator &I);
196 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000197 Instruction *visitShl(BinaryOperator &I);
198 Instruction *visitAShr(BinaryOperator &I);
199 Instruction *visitLShr(BinaryOperator &I);
200 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000201 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
202 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000203 Instruction *visitFCmpInst(FCmpInst &I);
204 Instruction *visitICmpInst(ICmpInst &I);
205 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000206 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
207 Instruction *LHS,
208 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000209 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
210 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000211
Reid Spencere4d87aa2006-12-23 06:05:41 +0000212 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
213 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000214 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000215 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000216 Instruction *commonCastTransforms(CastInst &CI);
217 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000218 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000219 Instruction *visitTrunc(TruncInst &CI);
220 Instruction *visitZExt(ZExtInst &CI);
221 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000222 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000223 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000224 Instruction *visitFPToUI(FPToUIInst &FI);
225 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000226 Instruction *visitUIToFP(CastInst &CI);
227 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000228 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000229 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000230 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000231 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
232 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000233 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000234 Instruction *visitSelectInst(SelectInst &SI);
235 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000236 Instruction *visitCallInst(CallInst &CI);
237 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000238 Instruction *visitPHINode(PHINode &PN);
239 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000240 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000241 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000242 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000243 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000244 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000245 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000246 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000247 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000248 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000249 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000250
251 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000252 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000253
Chris Lattner9fe38862003-06-19 17:00:31 +0000254 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000255 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000256 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000257 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000258 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
259 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000260 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000261 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
262
Chris Lattner9fe38862003-06-19 17:00:31 +0000263
Chris Lattner28977af2004-04-05 01:30:19 +0000264 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000265 // InsertNewInstBefore - insert an instruction New before instruction Old
266 // in the program. Add the new instruction to the worklist.
267 //
Chris Lattner955f3312004-09-28 21:48:02 +0000268 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000269 assert(New && New->getParent() == 0 &&
270 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000271 BasicBlock *BB = Old.getParent();
272 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000273 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000274 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000275 }
276
Chris Lattner0c967662004-09-24 15:21:34 +0000277 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
278 /// This also adds the cast to the worklist. Finally, this returns the
279 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000280 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
281 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000282 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000283
Chris Lattnere2ed0572006-04-06 19:19:17 +0000284 if (Constant *CV = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000285 return Context->getConstantExprCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000286
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000287 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000288 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000289 return C;
290 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000291
292 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
293 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
294 }
295
Chris Lattner0c967662004-09-24 15:21:34 +0000296
Chris Lattner8b170942002-08-09 23:47:40 +0000297 // ReplaceInstUsesWith - This method is to be used when an instruction is
298 // found to be dead, replacable with another preexisting expression. Here
299 // we add all uses of I to the worklist, replace all uses of I with the new
300 // value, then return I, so that the inst combiner will know that I was
301 // modified.
302 //
303 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000304 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000305 if (&I != V) {
306 I.replaceAllUsesWith(V);
307 return &I;
308 } else {
309 // If we are replacing the instruction with itself, this must be in a
310 // segment of unreachable code, so just clobber the instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +0000311 I.replaceAllUsesWith(Context->getUndef(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000312 return &I;
313 }
Chris Lattner8b170942002-08-09 23:47:40 +0000314 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000315
316 // EraseInstFromFunction - When dealing with an instruction that has side
317 // effects or produces a void value, we can't rely on DCE to delete the
318 // instruction. Instead, visit methods should return the value returned by
319 // this function.
320 Instruction *EraseInstFromFunction(Instruction &I) {
321 assert(I.use_empty() && "Cannot erase instruction that is used!");
322 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000323 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000324 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000325 return 0; // Don't do anything with FI
326 }
Chris Lattner173234a2008-06-02 01:18:21 +0000327
328 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
329 APInt &KnownOne, unsigned Depth = 0) const {
330 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
331 }
332
333 bool MaskedValueIsZero(Value *V, const APInt &Mask,
334 unsigned Depth = 0) const {
335 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
336 }
337 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
338 return llvm::ComputeNumSignBits(Op, TD, Depth);
339 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000340
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000341 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000342
Reid Spencere4d87aa2006-12-23 06:05:41 +0000343 /// SimplifyCommutative - This performs a few simplifications for
344 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000345 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000346
Reid Spencere4d87aa2006-12-23 06:05:41 +0000347 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
348 /// most-complex to least-complex order.
349 bool SimplifyCompare(CmpInst &I);
350
Chris Lattner886ab6c2009-01-31 08:15:18 +0000351 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
352 /// based on the demanded bits.
353 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
354 APInt& KnownZero, APInt& KnownOne,
355 unsigned Depth);
356 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000357 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000358 unsigned Depth=0);
359
360 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
361 /// SimplifyDemandedBits knows about. See if the instruction has any
362 /// properties that allow us to simplify its operands.
363 bool SimplifyDemandedInstructionBits(Instruction &Inst);
364
Evan Cheng388df622009-02-03 10:05:09 +0000365 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
366 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000367
Chris Lattner4e998b22004-09-29 05:07:12 +0000368 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
369 // PHI node as operand #0, see if we can fold the instruction into the PHI
370 // (which is only possible if all operands to the PHI are constants).
371 Instruction *FoldOpIntoPhi(Instruction &I);
372
Chris Lattnerbac32862004-11-14 19:13:23 +0000373 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
374 // operator and they all are only used by the PHI, PHI together their
375 // inputs, and do the operation once, to the result of the PHI.
376 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000377 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000378 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
379
Chris Lattner7da52b22006-11-01 04:51:18 +0000380
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000381 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
382 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000383
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000384 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000385 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000386 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000387 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000388 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000389 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000390 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000391 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000392 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000393
Chris Lattnerafe91a52006-06-15 19:07:26 +0000394
Reid Spencerc55b2432006-12-13 18:21:21 +0000395 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000396
Dan Gohman6de29f82009-06-15 22:12:54 +0000397 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000398 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000399 unsigned GetOrEnforceKnownAlignment(Value *V,
400 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000401
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000402 };
403}
404
Dan Gohman844731a2008-05-13 00:00:25 +0000405char InstCombiner::ID = 0;
406static RegisterPass<InstCombiner>
407X("instcombine", "Combine redundant instructions");
408
Chris Lattner4f98c562003-03-10 21:43:22 +0000409// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000410// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Owen Anderson0a5372e2009-07-13 04:09:18 +0000411static unsigned getComplexity(LLVMContext *Context, Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000412 if (isa<Instruction>(V)) {
Owen Anderson0a5372e2009-07-13 04:09:18 +0000413 if (BinaryOperator::isNeg(*Context, V) ||
414 BinaryOperator::isFNeg(*Context, V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000415 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000416 return 3;
417 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000418 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000419 if (isa<Argument>(V)) return 3;
420 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000421}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000422
Chris Lattnerc8802d22003-03-11 00:12:48 +0000423// isOnlyUse - Return true if this instruction will be deleted if we stop using
424// it.
425static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000426 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000427}
428
Chris Lattner4cb170c2004-02-23 06:38:22 +0000429// getPromotedType - Return the specified type promoted as it would be to pass
430// though a va_arg area...
431static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000432 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
433 if (ITy->getBitWidth() < 32)
434 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000435 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000436 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000437}
438
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000439/// getBitCastOperand - If the specified operand is a CastInst, a constant
440/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
441/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000442static Value *getBitCastOperand(Value *V) {
443 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000444 // BitCastInst?
Chris Lattnereed48272005-09-13 00:40:14 +0000445 return I->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000446 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
447 // GetElementPtrInst?
448 if (GEP->hasAllZeroIndices())
449 return GEP->getOperand(0);
450 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000451 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000452 // BitCast ConstantExp?
Chris Lattnereed48272005-09-13 00:40:14 +0000453 return CE->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000454 else if (CE->getOpcode() == Instruction::GetElementPtr) {
455 // GetElementPtr ConstantExp?
456 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
457 I != E; ++I) {
458 ConstantInt *CI = dyn_cast<ConstantInt>(I);
459 if (!CI || !CI->isZero())
460 // Any non-zero indices? Not cast-like.
461 return 0;
462 }
463 // All-zero indices? This is just like casting.
464 return CE->getOperand(0);
465 }
466 }
Chris Lattnereed48272005-09-13 00:40:14 +0000467 return 0;
468}
469
Reid Spencer3da59db2006-11-27 01:05:10 +0000470/// This function is a wrapper around CastInst::isEliminableCastPair. It
471/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000472static Instruction::CastOps
473isEliminableCastPair(
474 const CastInst *CI, ///< The first cast instruction
475 unsigned opcode, ///< The opcode of the second cast instruction
476 const Type *DstTy, ///< The target type for the second cast instruction
477 TargetData *TD ///< The target data for pointer size
478) {
479
480 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
481 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000482
Reid Spencer3da59db2006-11-27 01:05:10 +0000483 // Get the opcodes of the two Cast instructions
484 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
485 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000486
Chris Lattnera0e69692009-03-24 18:35:40 +0000487 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
488 DstTy, TD->getIntPtrType());
489
490 // We don't want to form an inttoptr or ptrtoint that converts to an integer
491 // type that differs from the pointer size.
492 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
493 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
494 Res = 0;
495
496 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000497}
498
499/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
500/// in any code being generated. It does not require codegen if V is simple
501/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000502static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
503 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000504 if (V->getType() == Ty || isa<Constant>(V)) return false;
505
Chris Lattner01575b72006-05-25 23:24:33 +0000506 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000507 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000508 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000509 return false;
510 return true;
511}
512
Chris Lattner4f98c562003-03-10 21:43:22 +0000513// SimplifyCommutative - This performs a few simplifications for commutative
514// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000515//
Chris Lattner4f98c562003-03-10 21:43:22 +0000516// 1. Order operands such that they are listed from right (least complex) to
517// left (most complex). This puts constants before unary operators before
518// binary operators.
519//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000520// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
521// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000522//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000523bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000524 bool Changed = false;
Owen Anderson0a5372e2009-07-13 04:09:18 +0000525 if (getComplexity(Context, I.getOperand(0)) <
526 getComplexity(Context, I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000527 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000528
Chris Lattner4f98c562003-03-10 21:43:22 +0000529 if (!I.isAssociative()) return Changed;
530 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000531 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
532 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
533 if (isa<Constant>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000534 Constant *Folded = Context->getConstantExpr(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000535 cast<Constant>(I.getOperand(1)),
536 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000537 I.setOperand(0, Op->getOperand(0));
538 I.setOperand(1, Folded);
539 return true;
540 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
541 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
542 isOnlyUse(Op) && isOnlyUse(Op1)) {
543 Constant *C1 = cast<Constant>(Op->getOperand(1));
544 Constant *C2 = cast<Constant>(Op1->getOperand(1));
545
546 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersond672ecb2009-07-03 00:17:18 +0000547 Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000548 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000549 Op1->getOperand(0),
550 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000551 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000552 I.setOperand(0, New);
553 I.setOperand(1, Folded);
554 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000555 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000556 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000557 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000558}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000559
Reid Spencere4d87aa2006-12-23 06:05:41 +0000560/// SimplifyCompare - For a CmpInst this function just orders the operands
561/// so that theyare listed from right (least complex) to left (most complex).
562/// This puts constants before unary operators before binary operators.
563bool InstCombiner::SimplifyCompare(CmpInst &I) {
Owen Anderson0a5372e2009-07-13 04:09:18 +0000564 if (getComplexity(Context, I.getOperand(0)) >=
565 getComplexity(Context, I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000566 return false;
567 I.swapOperands();
568 // Compare instructions are not associative so there's nothing else we can do.
569 return true;
570}
571
Chris Lattner8d969642003-03-10 23:06:50 +0000572// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
573// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000574//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000575static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
Owen Anderson0a5372e2009-07-13 04:09:18 +0000576 if (BinaryOperator::isNeg(*Context, V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000577 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000578
Chris Lattner0ce85802004-12-14 20:08:06 +0000579 // Constants can be considered to be negated values if they can be folded.
580 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000581 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000582
583 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
584 if (C->getType()->getElementType()->isInteger())
Owen Andersond672ecb2009-07-03 00:17:18 +0000585 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000586
Chris Lattner8d969642003-03-10 23:06:50 +0000587 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000588}
589
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000590// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
591// instruction if the LHS is a constant negative zero (which is the 'negate'
592// form).
593//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000594static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
Owen Anderson0a5372e2009-07-13 04:09:18 +0000595 if (BinaryOperator::isFNeg(*Context, V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000596 return BinaryOperator::getFNegArgument(V);
597
598 // Constants can be considered to be negated values if they can be folded.
599 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000600 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000601
602 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
603 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersond672ecb2009-07-03 00:17:18 +0000604 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000605
606 return 0;
607}
608
Owen Anderson07cf79e2009-07-06 23:00:19 +0000609static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
Chris Lattner8d969642003-03-10 23:06:50 +0000610 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000611 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000612
613 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000614 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000615 return Context->getConstantInt(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000616 return 0;
617}
618
Chris Lattnerc8802d22003-03-11 00:12:48 +0000619// dyn_castFoldableMul - If this value is a multiply that can be folded into
620// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000621// non-constant operand of the multiply, and set CST to point to the multiplier.
622// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000623//
Owen Andersond672ecb2009-07-03 00:17:18 +0000624static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000625 LLVMContext *Context) {
Chris Lattner42a75512007-01-15 02:27:26 +0000626 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000627 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000628 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000629 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000630 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000631 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000632 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000633 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000634 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000635 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Owen Andersond672ecb2009-07-03 00:17:18 +0000636 CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000637 return I->getOperand(0);
638 }
639 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000640 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000641}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000642
Chris Lattner574da9b2005-01-13 20:14:25 +0000643/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
644/// expression, return it.
645static User *dyn_castGetElementPtr(Value *V) {
646 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
647 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
648 if (CE->getOpcode() == Instruction::GetElementPtr)
649 return cast<User>(V);
650 return false;
651}
652
Dan Gohmaneee962e2008-04-10 18:43:06 +0000653/// getOpcode - If this is an Instruction or a ConstantExpr, return the
654/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000655static unsigned getOpcode(const Value *V) {
656 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000657 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000658 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000659 return CE->getOpcode();
660 // Use UserOp1 to mean there's no opcode.
661 return Instruction::UserOp1;
662}
663
Reid Spencer7177c3a2007-03-25 05:33:51 +0000664/// AddOne - Add one to a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000665static Constant *AddOne(Constant *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000666 return Context->getConstantExprAdd(C,
667 Context->getConstantInt(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000668}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000669/// SubOne - Subtract one from a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000670static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000671 return Context->getConstantExprSub(C,
672 Context->getConstantInt(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000673}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000674/// MultiplyOverflows - True if the multiply can not be expressed in an int
675/// this size.
Owen Andersond672ecb2009-07-03 00:17:18 +0000676static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000677 LLVMContext *Context) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000678 uint32_t W = C1->getBitWidth();
679 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
680 if (sign) {
681 LHSExt.sext(W * 2);
682 RHSExt.sext(W * 2);
683 } else {
684 LHSExt.zext(W * 2);
685 RHSExt.zext(W * 2);
686 }
687
688 APInt MulExt = LHSExt * RHSExt;
689
690 if (sign) {
691 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
692 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
693 return MulExt.slt(Min) || MulExt.sgt(Max);
694 } else
695 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
696}
Chris Lattner955f3312004-09-28 21:48:02 +0000697
Reid Spencere7816b52007-03-08 01:52:58 +0000698
Chris Lattner255d8912006-02-11 09:31:47 +0000699/// ShrinkDemandedConstant - Check to see if the specified operand of the
700/// specified instruction is a constant integer. If so, check to see if there
701/// are any bits set in the constant that are not demanded. If so, shrink the
702/// constant and return true.
703static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000704 APInt Demanded, LLVMContext *Context) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000705 assert(I && "No instruction?");
706 assert(OpNo < I->getNumOperands() && "Operand index too large");
707
708 // If the operand is not a constant integer, nothing to do.
709 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
710 if (!OpC) return false;
711
712 // If there are no bits set that aren't demanded, nothing to do.
713 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
714 if ((~Demanded & OpC->getValue()) == 0)
715 return false;
716
717 // This instruction is producing bits that are not demanded. Shrink the RHS.
718 Demanded &= OpC->getValue();
Owen Andersond672ecb2009-07-03 00:17:18 +0000719 I->setOperand(OpNo, Context->getConstantInt(Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000720 return true;
721}
722
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000723// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
724// set of known zero and one bits, compute the maximum and minimum values that
725// could have the specified known zero and known one bits, returning them in
726// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000727static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000728 const APInt& KnownOne,
729 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000730 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
731 KnownZero.getBitWidth() == Min.getBitWidth() &&
732 KnownZero.getBitWidth() == Max.getBitWidth() &&
733 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000734 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000735
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000736 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
737 // bit if it is unknown.
738 Min = KnownOne;
739 Max = KnownOne|UnknownBits;
740
Dan Gohman1c8491e2009-04-25 17:12:48 +0000741 if (UnknownBits.isNegative()) { // Sign bit is unknown
742 Min.set(Min.getBitWidth()-1);
743 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000744 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000745}
746
747// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
748// a set of known zero and one bits, compute the maximum and minimum values that
749// could have the specified known zero and known one bits, returning them in
750// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000751static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000752 const APInt &KnownOne,
753 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000754 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
755 KnownZero.getBitWidth() == Min.getBitWidth() &&
756 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000757 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000758 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000759
760 // The minimum value is when the unknown bits are all zeros.
761 Min = KnownOne;
762 // The maximum value is when the unknown bits are all ones.
763 Max = KnownOne|UnknownBits;
764}
Chris Lattner255d8912006-02-11 09:31:47 +0000765
Chris Lattner886ab6c2009-01-31 08:15:18 +0000766/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
767/// SimplifyDemandedBits knows about. See if the instruction has any
768/// properties that allow us to simplify its operands.
769bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000770 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000771 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
772 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
773
774 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
775 KnownZero, KnownOne, 0);
776 if (V == 0) return false;
777 if (V == &Inst) return true;
778 ReplaceInstUsesWith(Inst, V);
779 return true;
780}
781
782/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
783/// specified instruction operand if possible, updating it in place. It returns
784/// true if it made any change and false otherwise.
785bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
786 APInt &KnownZero, APInt &KnownOne,
787 unsigned Depth) {
788 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
789 KnownZero, KnownOne, Depth);
790 if (NewVal == 0) return false;
791 U.set(NewVal);
792 return true;
793}
794
795
796/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
797/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000798/// that only the bits set in DemandedMask of the result of V are ever used
799/// downstream. Consequently, depending on the mask and V, it may be possible
800/// to replace V with a constant or one of its operands. In such cases, this
801/// function does the replacement and returns true. In all other cases, it
802/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000803/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000804/// to be zero in the expression. These are provided to potentially allow the
805/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
806/// the expression. KnownOne and KnownZero always follow the invariant that
807/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
808/// the bits in KnownOne and KnownZero may only be accurate for those bits set
809/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
810/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000811///
812/// This returns null if it did not change anything and it permits no
813/// simplification. This returns V itself if it did some simplification of V's
814/// operands based on the information about what bits are demanded. This returns
815/// some other non-null value if it found out that V is equal to another value
816/// in the context where the specified bits are demanded, but not for all users.
817Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
818 APInt &KnownZero, APInt &KnownOne,
819 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000820 assert(V != 0 && "Null pointer of Value???");
821 assert(Depth <= 6 && "Limit Search Depth");
822 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000823 const Type *VTy = V->getType();
824 assert((TD || !isa<PointerType>(VTy)) &&
825 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000826 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
827 (!VTy->isIntOrIntVector() ||
828 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000829 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000830 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000831 "Value *V, DemandedMask, KnownZero and KnownOne "
832 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000833 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
834 // We know all of the bits for a constant!
835 KnownOne = CI->getValue() & DemandedMask;
836 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000837 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000838 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000839 if (isa<ConstantPointerNull>(V)) {
840 // We know all of the bits for a constant!
841 KnownOne.clear();
842 KnownZero = DemandedMask;
843 return 0;
844 }
845
Chris Lattner08d2cc72009-01-31 07:26:06 +0000846 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000847 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000848 if (DemandedMask == 0) { // Not demanding any bits from V.
849 if (isa<UndefValue>(V))
850 return 0;
Owen Andersond672ecb2009-07-03 00:17:18 +0000851 return Context->getUndef(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000852 }
853
Chris Lattner4598c942009-01-31 08:24:16 +0000854 if (Depth == 6) // Limit search depth.
855 return 0;
856
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000857 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
858 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
859
Dan Gohman1c8491e2009-04-25 17:12:48 +0000860 Instruction *I = dyn_cast<Instruction>(V);
861 if (!I) {
862 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
863 return 0; // Only analyze instructions.
864 }
865
Chris Lattner4598c942009-01-31 08:24:16 +0000866 // If there are multiple uses of this value and we aren't at the root, then
867 // we can't do any simplifications of the operands, because DemandedMask
868 // only reflects the bits demanded by *one* of the users.
869 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000870 // Despite the fact that we can't simplify this instruction in all User's
871 // context, we can at least compute the knownzero/knownone bits, and we can
872 // do simplifications that apply to *just* the one user if we know that
873 // this instruction has a simpler value in that context.
874 if (I->getOpcode() == Instruction::And) {
875 // If either the LHS or the RHS are Zero, the result is zero.
876 ComputeMaskedBits(I->getOperand(1), DemandedMask,
877 RHSKnownZero, RHSKnownOne, Depth+1);
878 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
879 LHSKnownZero, LHSKnownOne, Depth+1);
880
881 // If all of the demanded bits are known 1 on one side, return the other.
882 // These bits cannot contribute to the result of the 'and' in this
883 // context.
884 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
885 (DemandedMask & ~LHSKnownZero))
886 return I->getOperand(0);
887 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
888 (DemandedMask & ~RHSKnownZero))
889 return I->getOperand(1);
890
891 // If all of the demanded bits in the inputs are known zeros, return zero.
892 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000893 return Context->getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000894
895 } else if (I->getOpcode() == Instruction::Or) {
896 // We can simplify (X|Y) -> X or Y in the user's context if we know that
897 // only bits from X or Y are demanded.
898
899 // If either the LHS or the RHS are One, the result is One.
900 ComputeMaskedBits(I->getOperand(1), DemandedMask,
901 RHSKnownZero, RHSKnownOne, Depth+1);
902 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
903 LHSKnownZero, LHSKnownOne, Depth+1);
904
905 // If all of the demanded bits are known zero on one side, return the
906 // other. These bits cannot contribute to the result of the 'or' in this
907 // context.
908 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
909 (DemandedMask & ~LHSKnownOne))
910 return I->getOperand(0);
911 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
912 (DemandedMask & ~RHSKnownOne))
913 return I->getOperand(1);
914
915 // If all of the potentially set bits on one side are known to be set on
916 // the other side, just use the 'other' side.
917 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
918 (DemandedMask & (~RHSKnownZero)))
919 return I->getOperand(0);
920 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
921 (DemandedMask & (~LHSKnownZero)))
922 return I->getOperand(1);
923 }
924
Chris Lattner4598c942009-01-31 08:24:16 +0000925 // Compute the KnownZero/KnownOne bits to simplify things downstream.
926 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
927 return 0;
928 }
929
930 // If this is the root being simplified, allow it to have multiple uses,
931 // just set the DemandedMask to all bits so that we can try to simplify the
932 // operands. This allows visitTruncInst (for example) to simplify the
933 // operand of a trunc without duplicating all the logic below.
934 if (Depth == 0 && !V->hasOneUse())
935 DemandedMask = APInt::getAllOnesValue(BitWidth);
936
Reid Spencer8cb68342007-03-12 17:25:59 +0000937 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000938 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000939 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000940 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000941 case Instruction::And:
942 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000943 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
944 RHSKnownZero, RHSKnownOne, Depth+1) ||
945 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000946 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000947 return I;
948 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
949 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000950
951 // If all of the demanded bits are known 1 on one side, return the other.
952 // These bits cannot contribute to the result of the 'and'.
953 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
954 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000955 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000956 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
957 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000958 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000959
960 // If all of the demanded bits in the inputs are known zeros, return zero.
961 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000962 return Context->getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000963
964 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000965 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000966 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000967
968 // Output known-1 bits are only known if set in both the LHS & RHS.
969 RHSKnownOne &= LHSKnownOne;
970 // Output known-0 are known to be clear if zero in either the LHS | RHS.
971 RHSKnownZero |= LHSKnownZero;
972 break;
973 case Instruction::Or:
974 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000975 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
976 RHSKnownZero, RHSKnownOne, Depth+1) ||
977 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000978 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000979 return I;
980 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
981 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000982
983 // If all of the demanded bits are known zero on one side, return the other.
984 // These bits cannot contribute to the result of the 'or'.
985 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
986 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000987 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000988 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
989 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000990 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000991
992 // If all of the potentially set bits on one side are known to be set on
993 // the other side, just use the 'other' side.
994 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
995 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000996 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000997 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
998 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000999 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001000
1001 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +00001002 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001003 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001004
1005 // Output known-0 bits are only known if clear in both the LHS & RHS.
1006 RHSKnownZero &= LHSKnownZero;
1007 // Output known-1 are known to be set if set in either the LHS | RHS.
1008 RHSKnownOne |= LHSKnownOne;
1009 break;
1010 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001011 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1012 RHSKnownZero, RHSKnownOne, Depth+1) ||
1013 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001014 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001015 return I;
1016 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1017 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001018
1019 // If all of the demanded bits are known zero on one side, return the other.
1020 // These bits cannot contribute to the result of the 'xor'.
1021 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001022 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001023 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001024 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001025
1026 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1027 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1028 (RHSKnownOne & LHSKnownOne);
1029 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1030 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1031 (RHSKnownOne & LHSKnownZero);
1032
1033 // If all of the demanded bits are known to be zero on one side or the
1034 // other, turn this into an *inclusive* or.
1035 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1036 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1037 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001038 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001039 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001040 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001041 }
1042
1043 // If all of the demanded bits on one side are known, and all of the set
1044 // bits on that side are also known to be set on the other side, turn this
1045 // into an AND, as we know the bits will be cleared.
1046 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1047 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1048 // all known
1049 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001050 Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001051 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001052 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001053 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001054 }
1055 }
1056
1057 // If the RHS is a constant, see if we can simplify it.
1058 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Owen Andersond672ecb2009-07-03 00:17:18 +00001059 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001060 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001061
1062 RHSKnownZero = KnownZeroOut;
1063 RHSKnownOne = KnownOneOut;
1064 break;
1065 }
1066 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001067 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1068 RHSKnownZero, RHSKnownOne, Depth+1) ||
1069 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001070 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001071 return I;
1072 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1073 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001074
1075 // If the operands are constants, see if we can simplify them.
Owen Andersond672ecb2009-07-03 00:17:18 +00001076 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1077 ShrinkDemandedConstant(I, 2, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001078 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001079
1080 // Only known if known in both the LHS and RHS.
1081 RHSKnownOne &= LHSKnownOne;
1082 RHSKnownZero &= LHSKnownZero;
1083 break;
1084 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001085 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001086 DemandedMask.zext(truncBf);
1087 RHSKnownZero.zext(truncBf);
1088 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001089 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001090 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001091 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001092 DemandedMask.trunc(BitWidth);
1093 RHSKnownZero.trunc(BitWidth);
1094 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001095 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001096 break;
1097 }
1098 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001099 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001100 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001101
1102 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1103 if (const VectorType *SrcVTy =
1104 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1105 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1106 // Don't touch a bitcast between vectors of different element counts.
1107 return false;
1108 } else
1109 // Don't touch a scalar-to-vector bitcast.
1110 return false;
1111 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1112 // Don't touch a vector-to-scalar bitcast.
1113 return false;
1114
Chris Lattner886ab6c2009-01-31 08:15:18 +00001115 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001116 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001117 return I;
1118 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001119 break;
1120 case Instruction::ZExt: {
1121 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001122 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001123
Zhou Shengd48653a2007-03-29 04:45:55 +00001124 DemandedMask.trunc(SrcBitWidth);
1125 RHSKnownZero.trunc(SrcBitWidth);
1126 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001127 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001128 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001129 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001130 DemandedMask.zext(BitWidth);
1131 RHSKnownZero.zext(BitWidth);
1132 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001133 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001134 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001135 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001136 break;
1137 }
1138 case Instruction::SExt: {
1139 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001140 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001141
Reid Spencer8cb68342007-03-12 17:25:59 +00001142 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001143 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001144
Zhou Sheng01542f32007-03-29 02:26:30 +00001145 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001146 // If any of the sign extended bits are demanded, we know that the sign
1147 // bit is demanded.
1148 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001149 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001150
Zhou Shengd48653a2007-03-29 04:45:55 +00001151 InputDemandedBits.trunc(SrcBitWidth);
1152 RHSKnownZero.trunc(SrcBitWidth);
1153 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001154 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001155 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001156 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001157 InputDemandedBits.zext(BitWidth);
1158 RHSKnownZero.zext(BitWidth);
1159 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001160 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001161
1162 // If the sign bit of the input is known set or clear, then we know the
1163 // top bits of the result.
1164
1165 // If the input sign bit is known zero, or if the NewBits are not demanded
1166 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001167 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001168 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001169 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1170 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001171 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001172 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001173 }
1174 break;
1175 }
1176 case Instruction::Add: {
1177 // Figure out what the input bits are. If the top bits of the and result
1178 // are not demanded, then the add doesn't demand them from its input
1179 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001180 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001181
1182 // If there is a constant on the RHS, there are a variety of xformations
1183 // we can do.
1184 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1185 // If null, this should be simplified elsewhere. Some of the xforms here
1186 // won't work if the RHS is zero.
1187 if (RHS->isZero())
1188 break;
1189
1190 // If the top bit of the output is demanded, demand everything from the
1191 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001192 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001193
1194 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001195 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001196 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001197 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001198
1199 // If the RHS of the add has bits set that can't affect the input, reduce
1200 // the constant.
Owen Andersond672ecb2009-07-03 00:17:18 +00001201 if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001202 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001203
1204 // Avoid excess work.
1205 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1206 break;
1207
1208 // Turn it into OR if input bits are zero.
1209 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1210 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001211 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001212 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001213 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001214 }
1215
1216 // We can say something about the output known-zero and known-one bits,
1217 // depending on potential carries from the input constant and the
1218 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1219 // bits set and the RHS constant is 0x01001, then we know we have a known
1220 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1221
1222 // To compute this, we first compute the potential carry bits. These are
1223 // the bits which may be modified. I'm not aware of a better way to do
1224 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001225 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001226 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001227
1228 // Now that we know which bits have carries, compute the known-1/0 sets.
1229
1230 // Bits are known one if they are known zero in one operand and one in the
1231 // other, and there is no input carry.
1232 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1233 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1234
1235 // Bits are known zero if they are known zero in both operands and there
1236 // is no input carry.
1237 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1238 } else {
1239 // If the high-bits of this ADD are not demanded, then it does not demand
1240 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001241 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001242 // Right fill the mask of bits for this ADD to demand the most
1243 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001244 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001245 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1246 LHSKnownZero, LHSKnownOne, Depth+1) ||
1247 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001248 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001249 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001250 }
1251 }
1252 break;
1253 }
1254 case Instruction::Sub:
1255 // If the high-bits of this SUB are not demanded, then it does not demand
1256 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001257 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001258 // Right fill the mask of bits for this SUB to demand the most
1259 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001260 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001261 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001262 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1263 LHSKnownZero, LHSKnownOne, Depth+1) ||
1264 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001265 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001266 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001267 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001268 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1269 // the known zeros and ones.
1270 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001271 break;
1272 case Instruction::Shl:
1273 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001274 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001275 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001276 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001277 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001278 return I;
1279 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001280 RHSKnownZero <<= ShiftAmt;
1281 RHSKnownOne <<= ShiftAmt;
1282 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001283 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001284 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001285 }
1286 break;
1287 case Instruction::LShr:
1288 // For a logical shift right
1289 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001290 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001291
Reid Spencer8cb68342007-03-12 17:25:59 +00001292 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001293 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001294 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001295 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001296 return I;
1297 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001298 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1299 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001300 if (ShiftAmt) {
1301 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001302 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001303 RHSKnownZero |= HighBits; // high bits known zero.
1304 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001305 }
1306 break;
1307 case Instruction::AShr:
1308 // If this is an arithmetic shift right and only the low-bit is set, we can
1309 // always convert this into a logical shr, even if the shift amount is
1310 // variable. The low bit of the shift cannot be an input sign bit unless
1311 // the shift amount is >= the size of the datatype, which is undefined.
1312 if (DemandedMask == 1) {
1313 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001314 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001315 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001316 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001317 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001318
1319 // If the sign bit is the only bit demanded by this ashr, then there is no
1320 // need to do it, the shift doesn't change the high bit.
1321 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001322 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001323
1324 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001325 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001326
Reid Spencer8cb68342007-03-12 17:25:59 +00001327 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001328 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001329 // If any of the "high bits" are demanded, we should set the sign bit as
1330 // demanded.
1331 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1332 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001333 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001334 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001335 return I;
1336 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001337 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001338 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001339 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1340 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1341
1342 // Handle the sign bits.
1343 APInt SignBit(APInt::getSignBit(BitWidth));
1344 // Adjust to where it is now in the mask.
1345 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1346
1347 // If the input sign bit is known to be zero, or if none of the top bits
1348 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001349 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001350 (HighBits & ~DemandedMask) == HighBits) {
1351 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001352 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001353 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001354 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001355 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1356 RHSKnownOne |= HighBits;
1357 }
1358 }
1359 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001360 case Instruction::SRem:
1361 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001362 APInt RA = Rem->getValue().abs();
1363 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001364 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001365 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001366
Nick Lewycky8e394322008-11-02 02:41:50 +00001367 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001368 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001369 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001370 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001371 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001372
1373 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1374 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001375
1376 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001377
Chris Lattner886ab6c2009-01-31 08:15:18 +00001378 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001379 }
1380 }
1381 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001382 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001383 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1384 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001385 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1386 KnownZero2, KnownOne2, Depth+1) ||
1387 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001388 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001389 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001390
Chris Lattner455e9ab2009-01-21 18:09:24 +00001391 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001392 Leaders = std::max(Leaders,
1393 KnownZero2.countLeadingOnes());
1394 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001395 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001396 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001397 case Instruction::Call:
1398 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1399 switch (II->getIntrinsicID()) {
1400 default: break;
1401 case Intrinsic::bswap: {
1402 // If the only bits demanded come from one byte of the bswap result,
1403 // just shift the input byte into position to eliminate the bswap.
1404 unsigned NLZ = DemandedMask.countLeadingZeros();
1405 unsigned NTZ = DemandedMask.countTrailingZeros();
1406
1407 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1408 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1409 // have 14 leading zeros, round to 8.
1410 NLZ &= ~7;
1411 NTZ &= ~7;
1412 // If we need exactly one byte, we can do this transformation.
1413 if (BitWidth-NLZ-NTZ == 8) {
1414 unsigned ResultBit = NTZ;
1415 unsigned InputBit = BitWidth-NTZ-8;
1416
1417 // Replace this with either a left or right shift to get the byte into
1418 // the right place.
1419 Instruction *NewVal;
1420 if (InputBit > ResultBit)
1421 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00001422 Context->getConstantInt(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001423 else
1424 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00001425 Context->getConstantInt(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001426 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001427 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001428 }
1429
1430 // TODO: Could compute known zero/one bits based on the input.
1431 break;
1432 }
1433 }
1434 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001435 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001436 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001437 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001438
1439 // If the client is only demanding bits that we know, return the known
1440 // constant.
Dan Gohman1c8491e2009-04-25 17:12:48 +00001441 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001442 Constant *C = Context->getConstantInt(RHSKnownOne);
Dan Gohman1c8491e2009-04-25 17:12:48 +00001443 if (isa<PointerType>(V->getType()))
Owen Andersond672ecb2009-07-03 00:17:18 +00001444 C = Context->getConstantExprIntToPtr(C, V->getType());
Dan Gohman1c8491e2009-04-25 17:12:48 +00001445 return C;
1446 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001447 return false;
1448}
1449
Chris Lattner867b99f2006-10-05 06:55:50 +00001450
Mon P Wangaeb06d22008-11-10 04:46:22 +00001451/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001452/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001453/// actually used by the caller. This method analyzes which elements of the
1454/// operand are undef and returns that information in UndefElts.
1455///
1456/// If the information about demanded elements can be used to simplify the
1457/// operation, the operation is simplified, then the resultant value is
1458/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001459Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1460 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001461 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001462 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001463 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001464 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001465
1466 if (isa<UndefValue>(V)) {
1467 // If the entire vector is undefined, just return this info.
1468 UndefElts = EltMask;
1469 return 0;
1470 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1471 UndefElts = EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001472 return Context->getUndef(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001473 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001474
Chris Lattner867b99f2006-10-05 06:55:50 +00001475 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001476 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1477 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001478 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001479
1480 std::vector<Constant*> Elts;
1481 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001482 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001483 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001484 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001485 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1486 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001487 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001488 } else { // Otherwise, defined.
1489 Elts.push_back(CP->getOperand(i));
1490 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001491
Chris Lattner867b99f2006-10-05 06:55:50 +00001492 // If we changed the constant, return it.
Owen Andersond672ecb2009-07-03 00:17:18 +00001493 Constant *NewCP = Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001494 return NewCP != CP ? NewCP : 0;
1495 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001496 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001497 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001498
1499 // Check if this is identity. If so, return 0 since we are not simplifying
1500 // anything.
1501 if (DemandedElts == ((1ULL << VWidth) -1))
1502 return 0;
1503
Reid Spencer9d6565a2007-02-15 02:26:10 +00001504 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001505 Constant *Zero = Context->getNullValue(EltTy);
1506 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001507 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001508 for (unsigned i = 0; i != VWidth; ++i) {
1509 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1510 Elts.push_back(Elt);
1511 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001512 UndefElts = DemandedElts ^ EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001513 return Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001514 }
1515
Dan Gohman488fbfc2008-09-09 18:11:14 +00001516 // Limit search depth.
1517 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001518 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001519
1520 // If multiple users are using the root value, procede with
1521 // simplification conservatively assuming that all elements
1522 // are needed.
1523 if (!V->hasOneUse()) {
1524 // Quit if we find multiple users of a non-root value though.
1525 // They'll be handled when it's their turn to be visited by
1526 // the main instcombine process.
1527 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001528 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001529 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001530
1531 // Conservatively assume that all elements are needed.
1532 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001533 }
1534
1535 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001536 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001537
1538 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001539 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001540 Value *TmpV;
1541 switch (I->getOpcode()) {
1542 default: break;
1543
1544 case Instruction::InsertElement: {
1545 // If this is a variable index, we don't know which element it overwrites.
1546 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001547 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001548 if (Idx == 0) {
1549 // Note that we can't propagate undef elt info, because we don't know
1550 // which elt is getting updated.
1551 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1552 UndefElts2, Depth+1);
1553 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1554 break;
1555 }
1556
1557 // If this is inserting an element that isn't demanded, remove this
1558 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001559 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001560 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001561 return AddSoonDeadInstToWorklist(*I, 0);
1562
1563 // Otherwise, the element inserted overwrites whatever was there, so the
1564 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001565 APInt DemandedElts2 = DemandedElts;
1566 DemandedElts2.clear(IdxNo);
1567 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001568 UndefElts, Depth+1);
1569 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1570
1571 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001572 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001573 break;
1574 }
1575 case Instruction::ShuffleVector: {
1576 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001577 uint64_t LHSVWidth =
1578 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001579 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001580 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001581 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001582 unsigned MaskVal = Shuffle->getMaskValue(i);
1583 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001584 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001585 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001586 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001587 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001588 else
Evan Cheng388df622009-02-03 10:05:09 +00001589 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001590 }
1591 }
1592 }
1593
Nate Begeman7b254672009-02-11 22:36:25 +00001594 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001595 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001596 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001597 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1598
Nate Begeman7b254672009-02-11 22:36:25 +00001599 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001600 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1601 UndefElts3, Depth+1);
1602 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1603
1604 bool NewUndefElts = false;
1605 for (unsigned i = 0; i < VWidth; i++) {
1606 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001607 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001608 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001609 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001610 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001611 NewUndefElts = true;
1612 UndefElts.set(i);
1613 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001614 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001615 if (UndefElts3[MaskVal - LHSVWidth]) {
1616 NewUndefElts = true;
1617 UndefElts.set(i);
1618 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001619 }
1620 }
1621
1622 if (NewUndefElts) {
1623 // Add additional discovered undefs.
1624 std::vector<Constant*> Elts;
1625 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001626 if (UndefElts[i])
Owen Andersond672ecb2009-07-03 00:17:18 +00001627 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001628 else
Owen Andersond672ecb2009-07-03 00:17:18 +00001629 Elts.push_back(Context->getConstantInt(Type::Int32Ty,
Dan Gohman488fbfc2008-09-09 18:11:14 +00001630 Shuffle->getMaskValue(i)));
1631 }
Owen Andersond672ecb2009-07-03 00:17:18 +00001632 I->setOperand(2, Context->getConstantVector(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001633 MadeChange = true;
1634 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001635 break;
1636 }
Chris Lattner69878332007-04-14 22:29:23 +00001637 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001638 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001639 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1640 if (!VTy) break;
1641 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001642 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001643 unsigned Ratio;
1644
1645 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001646 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001647 // elements as are demanded of us.
1648 Ratio = 1;
1649 InputDemandedElts = DemandedElts;
1650 } else if (VWidth > InVWidth) {
1651 // Untested so far.
1652 break;
1653
1654 // If there are more elements in the result than there are in the source,
1655 // then an input element is live if any of the corresponding output
1656 // elements are live.
1657 Ratio = VWidth/InVWidth;
1658 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001659 if (DemandedElts[OutIdx])
1660 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001661 }
1662 } else {
1663 // Untested so far.
1664 break;
1665
1666 // If there are more elements in the source than there are in the result,
1667 // then an input element is live if the corresponding output element is
1668 // live.
1669 Ratio = InVWidth/VWidth;
1670 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001671 if (DemandedElts[InIdx/Ratio])
1672 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001673 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001674
Chris Lattner69878332007-04-14 22:29:23 +00001675 // div/rem demand all inputs, because they don't want divide by zero.
1676 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1677 UndefElts2, Depth+1);
1678 if (TmpV) {
1679 I->setOperand(0, TmpV);
1680 MadeChange = true;
1681 }
1682
1683 UndefElts = UndefElts2;
1684 if (VWidth > InVWidth) {
Torok Edwinc25e7582009-07-11 20:10:48 +00001685 LLVM_UNREACHABLE("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001686 // If there are more elements in the result than there are in the source,
1687 // then an output element is undef if the corresponding input element is
1688 // undef.
1689 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001690 if (UndefElts2[OutIdx/Ratio])
1691 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001692 } else if (VWidth < InVWidth) {
Torok Edwinc25e7582009-07-11 20:10:48 +00001693 LLVM_UNREACHABLE("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001694 // If there are more elements in the source than there are in the result,
1695 // then a result element is undef if all of the corresponding input
1696 // elements are undef.
1697 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1698 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001699 if (!UndefElts2[InIdx]) // Not undef?
1700 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001701 }
1702 break;
1703 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001704 case Instruction::And:
1705 case Instruction::Or:
1706 case Instruction::Xor:
1707 case Instruction::Add:
1708 case Instruction::Sub:
1709 case Instruction::Mul:
1710 // div/rem demand all inputs, because they don't want divide by zero.
1711 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1712 UndefElts, Depth+1);
1713 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1714 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1715 UndefElts2, Depth+1);
1716 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1717
1718 // Output elements are undefined if both are undefined. Consider things
1719 // like undef&0. The result is known zero, not undef.
1720 UndefElts &= UndefElts2;
1721 break;
1722
1723 case Instruction::Call: {
1724 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1725 if (!II) break;
1726 switch (II->getIntrinsicID()) {
1727 default: break;
1728
1729 // Binary vector operations that work column-wise. A dest element is a
1730 // function of the corresponding input elements from the two inputs.
1731 case Intrinsic::x86_sse_sub_ss:
1732 case Intrinsic::x86_sse_mul_ss:
1733 case Intrinsic::x86_sse_min_ss:
1734 case Intrinsic::x86_sse_max_ss:
1735 case Intrinsic::x86_sse2_sub_sd:
1736 case Intrinsic::x86_sse2_mul_sd:
1737 case Intrinsic::x86_sse2_min_sd:
1738 case Intrinsic::x86_sse2_max_sd:
1739 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1740 UndefElts, Depth+1);
1741 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1742 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1743 UndefElts2, Depth+1);
1744 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1745
1746 // If only the low elt is demanded and this is a scalarizable intrinsic,
1747 // scalarize it now.
1748 if (DemandedElts == 1) {
1749 switch (II->getIntrinsicID()) {
1750 default: break;
1751 case Intrinsic::x86_sse_sub_ss:
1752 case Intrinsic::x86_sse_mul_ss:
1753 case Intrinsic::x86_sse2_sub_sd:
1754 case Intrinsic::x86_sse2_mul_sd:
1755 // TODO: Lower MIN/MAX/ABS/etc
1756 Value *LHS = II->getOperand(1);
1757 Value *RHS = II->getOperand(2);
1758 // Extract the element as scalars.
1759 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1760 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1761
1762 switch (II->getIntrinsicID()) {
Torok Edwinc25e7582009-07-11 20:10:48 +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(
1778 Context->getUndef(II->getType()), TmpV, 0U, II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001779 InsertNewInstBefore(New, *II);
1780 AddSoonDeadInstToWorklist(*II, 0);
1781 return New;
1782 }
1783 }
1784
1785 // Output elements are undefined if both are undefined. Consider things
1786 // like undef&0. The result is known zero, not undef.
1787 UndefElts &= UndefElts2;
1788 break;
1789 }
1790 break;
1791 }
1792 }
1793 return MadeChange ? I : 0;
1794}
1795
Dan Gohman45b4e482008-05-19 22:14:15 +00001796
Chris Lattner564a7272003-08-13 19:01:45 +00001797/// AssociativeOpt - Perform an optimization on an associative operator. This
1798/// function is designed to check a chain of associative operators for a
1799/// potential to apply a certain optimization. Since the optimization may be
1800/// applicable if the expression was reassociated, this checks the chain, then
1801/// reassociates the expression as necessary to expose the optimization
1802/// opportunity. This makes use of a special Functor, which must define
1803/// 'shouldApply' and 'apply' methods.
1804///
1805template<typename Functor>
Owen Andersond672ecb2009-07-03 00:17:18 +00001806static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001807 LLVMContext *Context) {
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 Andersond672ecb2009-07-03 00:17:18 +00001840 Root.replaceAllUsesWith(Context->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;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001879 LLVMContext *Context;
1880 AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001881 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1882 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001883 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00001884 Context->getConstantInt(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001885 }
1886};
1887
1888// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1889// iff C1&C2 == 0
1890struct AddMaskingAnd {
1891 Constant *C2;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001892 LLVMContext *Context;
1893 AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001894 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001895 ConstantInt *C1;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00001896 return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
Owen Andersond672ecb2009-07-03 00:17:18 +00001897 Context->getConstantExprAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001898 }
1899 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001900 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001901 }
1902};
1903
Dan Gohman844731a2008-05-13 00:00:25 +00001904}
1905
Chris Lattner6e7ba452005-01-01 16:22:27 +00001906static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001907 InstCombiner *IC) {
Owen Anderson07cf79e2009-07-06 23:00:19 +00001908 LLVMContext *Context = IC->getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00001909
Reid Spencer3da59db2006-11-27 01:05:10 +00001910 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001911 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001912 }
1913
Chris Lattner2eefe512004-04-09 19:05:30 +00001914 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001915 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1916 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001917
Chris Lattner2eefe512004-04-09 19:05:30 +00001918 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1919 if (ConstIsRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00001920 return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1921 return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001922 }
1923
1924 Value *Op0 = SO, *Op1 = ConstOperand;
1925 if (!ConstIsRHS)
1926 std::swap(Op0, Op1);
1927 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001928 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001929 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001930 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00001931 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1932 Op0, Op1, SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001933 else {
Torok Edwin7d696d82009-07-11 13:10:19 +00001934 LLVM_UNREACHABLE("Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001935 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001936 return IC->InsertNewInstBefore(New, I);
1937}
1938
1939// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1940// constant as the other operand, try to fold the binary operator into the
1941// select arguments. This also works for Cast instructions, which obviously do
1942// not have a second operand.
1943static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1944 InstCombiner *IC) {
1945 // Don't modify shared select instructions
1946 if (!SI->hasOneUse()) return 0;
1947 Value *TV = SI->getOperand(1);
1948 Value *FV = SI->getOperand(2);
1949
1950 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001951 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001952 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001953
Chris Lattner6e7ba452005-01-01 16:22:27 +00001954 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1955 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1956
Gabor Greif051a9502008-04-06 20:25:17 +00001957 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1958 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001959 }
1960 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001961}
1962
Chris Lattner4e998b22004-09-29 05:07:12 +00001963
1964/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1965/// node as operand #0, see if we can fold the instruction into the PHI (which
1966/// is only possible if all operands to the PHI are constants).
1967Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1968 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001969 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001970 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001971
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001972 // Check to see if all of the operands of the PHI are constants. If there is
1973 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001974 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001975 BasicBlock *NonConstBB = 0;
1976 for (unsigned i = 0; i != NumPHIValues; ++i)
1977 if (!isa<Constant>(PN->getIncomingValue(i))) {
1978 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001979 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001980 NonConstBB = PN->getIncomingBlock(i);
1981
1982 // If the incoming non-constant value is in I's block, we have an infinite
1983 // loop.
1984 if (NonConstBB == I.getParent())
1985 return 0;
1986 }
1987
1988 // If there is exactly one non-constant value, we can insert a copy of the
1989 // operation in that block. However, if this is a critical edge, we would be
1990 // inserting the computation one some other paths (e.g. inside a loop). Only
1991 // do this if the pred block is unconditionally branching into the phi block.
1992 if (NonConstBB) {
1993 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1994 if (!BI || !BI->isUnconditional()) return 0;
1995 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001996
1997 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001998 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001999 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002000 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002001 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002002
2003 // Next, add all of the operands to the PHI.
2004 if (I.getNumOperands() == 2) {
2005 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002006 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002007 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002008 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002009 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersond672ecb2009-07-03 00:17:18 +00002010 InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002011 else
Owen Andersond672ecb2009-07-03 00:17:18 +00002012 InV = Context->getConstantExpr(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002013 } else {
2014 assert(PN->getIncomingBlock(i) == NonConstBB);
2015 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002016 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002017 PN->getIncomingValue(i), C, "phitmp",
2018 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002019 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00002020 InV = CmpInst::Create(*Context, CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002021 CI->getPredicate(),
2022 PN->getIncomingValue(i), C, "phitmp",
2023 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002024 else
Torok Edwinc25e7582009-07-11 20:10:48 +00002025 LLVM_UNREACHABLE("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002026
Chris Lattnerdbab3862007-03-02 21:28:56 +00002027 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002028 }
2029 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002030 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002031 } else {
2032 CastInst *CI = cast<CastInst>(&I);
2033 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002034 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002035 Value *InV;
2036 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002037 InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002038 } else {
2039 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002040 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002041 I.getType(), "phitmp",
2042 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002043 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002044 }
2045 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002046 }
2047 }
2048 return ReplaceInstUsesWith(I, NewPN);
2049}
2050
Chris Lattner2454a2e2008-01-29 06:52:45 +00002051
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002052/// WillNotOverflowSignedAdd - Return true if we can prove that:
2053/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2054/// This basically requires proving that the add in the original type would not
2055/// overflow to change the sign bit or have a carry out.
2056bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2057 // There are different heuristics we can use for this. Here are some simple
2058 // ones.
2059
2060 // Add has the property that adding any two 2's complement numbers can only
2061 // have one carry bit which can change a sign. As such, if LHS and RHS each
2062 // have at least two sign bits, we know that the addition of the two values will
2063 // sign extend fine.
2064 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2065 return true;
2066
2067
2068 // If one of the operands only has one non-zero bit, and if the other operand
2069 // has a known-zero bit in a more significant place than it (not including the
2070 // sign bit) the ripple may go up to and fill the zero, but won't change the
2071 // sign. For example, (X & ~4) + 1.
2072
2073 // TODO: Implement.
2074
2075 return false;
2076}
2077
Chris Lattner2454a2e2008-01-29 06:52:45 +00002078
Chris Lattner7e708292002-06-25 16:13:24 +00002079Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002080 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002081 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002082
Chris Lattner66331a42004-04-10 22:01:55 +00002083 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002084 // X + undef -> undef
2085 if (isa<UndefValue>(RHS))
2086 return ReplaceInstUsesWith(I, RHS);
2087
Chris Lattner66331a42004-04-10 22:01:55 +00002088 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002089 if (RHSC->isNullValue())
2090 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002091
Chris Lattner66331a42004-04-10 22:01:55 +00002092 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002093 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002094 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002095 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002096 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002097 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002098
2099 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2100 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002101 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002102 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002103
2104 // zext(i1) - 1 -> select i1, 0, -1
2105 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2106 if (CI->isAllOnesValue() &&
2107 ZI->getOperand(0)->getType() == Type::Int1Ty)
2108 return SelectInst::Create(ZI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002109 Context->getNullValue(I.getType()),
Owen Anderson73c6b712009-07-13 20:58:05 +00002110 Context->getAllOnesValue(I.getType()));
Chris Lattner66331a42004-04-10 22:01:55 +00002111 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002112
2113 if (isa<PHINode>(LHS))
2114 if (Instruction *NV = FoldOpIntoPhi(I))
2115 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002116
Chris Lattner4f637d42006-01-06 17:59:59 +00002117 ConstantInt *XorRHS = 0;
2118 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002119 if (isa<ConstantInt>(RHSC) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002120 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002121 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002122 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002123
Zhou Sheng4351c642007-04-02 08:20:41 +00002124 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002125 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2126 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002127 do {
2128 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002129 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2130 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002131 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2132 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002133 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002134 if (!MaskedValueIsZero(XorLHS,
2135 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002136 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002137 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002138 }
2139 }
2140 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002141 C0080Val = APIntOps::lshr(C0080Val, Size);
2142 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2143 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002144
Reid Spencer35c38852007-03-28 01:36:16 +00002145 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002146 // with funny bit widths then this switch statement should be removed. It
2147 // is just here to get the size of the "middle" type back up to something
2148 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002149 const Type *MiddleType = 0;
2150 switch (Size) {
2151 default: break;
2152 case 32: MiddleType = Type::Int32Ty; break;
2153 case 16: MiddleType = Type::Int16Ty; break;
2154 case 8: MiddleType = Type::Int8Ty; break;
2155 }
2156 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002157 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002158 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002159 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002160 }
2161 }
Chris Lattner66331a42004-04-10 22:01:55 +00002162 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002163
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002164 if (I.getType() == Type::Int1Ty)
2165 return BinaryOperator::CreateXor(LHS, RHS);
2166
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002167 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002168 if (I.getType()->isInteger()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002169 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2170 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002171
2172 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2173 if (RHSI->getOpcode() == Instruction::Sub)
2174 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2175 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2176 }
2177 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2178 if (LHSI->getOpcode() == Instruction::Sub)
2179 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2180 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2181 }
Robert Bocchino71698282004-07-27 21:02:21 +00002182 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002183
Chris Lattner5c4afb92002-05-08 22:46:53 +00002184 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002185 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002186 if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002187 if (LHS->getType()->isIntOrIntVector()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002188 if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002189 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002190 InsertNewInstBefore(NewAdd, I);
Owen Anderson0a5372e2009-07-13 04:09:18 +00002191 return BinaryOperator::CreateNeg(*Context, NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002192 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002193 }
2194
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002195 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002196 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002197
2198 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002199 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002200 if (Value *V = dyn_castNegVal(RHS, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002201 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002202
Misha Brukmanfd939082005-04-21 23:48:37 +00002203
Chris Lattner50af16a2004-11-13 19:50:12 +00002204 ConstantInt *C2;
Owen Andersond672ecb2009-07-03 00:17:18 +00002205 if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002206 if (X == RHS) // X*C + X --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002207 return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002208
2209 // X*C1 + X*C2 --> X * (C1+C2)
2210 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002211 if (X == dyn_castFoldableMul(RHS, C1, Context))
2212 return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002213 }
2214
2215 // X + X*C --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002216 if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2217 return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002218
Chris Lattnere617c9e2007-01-05 02:17:46 +00002219 // X + ~X --> -1 since ~X = -X-1
Owen Andersond672ecb2009-07-03 00:17:18 +00002220 if (dyn_castNotVal(LHS, Context) == RHS ||
2221 dyn_castNotVal(RHS, Context) == LHS)
2222 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002223
Chris Lattnerad3448c2003-02-18 19:57:07 +00002224
Chris Lattner564a7272003-08-13 19:01:45 +00002225 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002226 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002227 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002228 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002229
2230 // A+B --> A|B iff A and B have no bits set in common.
2231 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2232 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2233 APInt LHSKnownOne(IT->getBitWidth(), 0);
2234 APInt LHSKnownZero(IT->getBitWidth(), 0);
2235 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2236 if (LHSKnownZero != 0) {
2237 APInt RHSKnownOne(IT->getBitWidth(), 0);
2238 APInt RHSKnownZero(IT->getBitWidth(), 0);
2239 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2240
2241 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002242 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002243 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002244 }
2245 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002246
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002247 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002248 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002249 Value *W, *X, *Y, *Z;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002250 if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2251 match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002252 if (W != Y) {
2253 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002254 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002255 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002256 std::swap(W, X);
2257 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002258 std::swap(Y, Z);
2259 std::swap(W, X);
2260 }
2261 }
2262
2263 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002264 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002265 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002266 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002267 }
2268 }
2269 }
2270
Chris Lattner6b032052003-10-02 15:11:26 +00002271 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002272 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002273 if (match(LHS, m_Not(m_Value(X)), *Context)) // ~X + C --> (C-1) - X
Owen Andersond672ecb2009-07-03 00:17:18 +00002274 return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002275
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002276 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002277 if (LHS->hasOneUse() &&
2278 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002279 Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002280 if (Anded == CRHS) {
2281 // See if all bits from the first bit set in the Add RHS up are included
2282 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002283 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002284
2285 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002286 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002287
2288 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002289 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002290
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002291 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2292 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002293 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002294 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002295 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002296 }
2297 }
2298 }
2299
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002300 // Try to fold constant add into select arguments.
2301 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002302 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002303 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002304 }
2305
Reid Spencer1628cec2006-10-26 06:15:43 +00002306 // add (cast *A to intptrtype) B ->
Dan Gohmana119de82009-06-14 23:30:43 +00002307 // cast (GEP (cast *A to i8*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002308 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002309 CastInst *CI = dyn_cast<CastInst>(LHS);
2310 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002311 if (!CI) {
2312 CI = dyn_cast<CastInst>(RHS);
2313 Other = LHS;
2314 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002315 if (CI && CI->getType()->isSized() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00002316 (CI->getType()->getScalarSizeInBits() ==
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002317 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002318 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002319 unsigned AS =
2320 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002321 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002322 Context->getPointerType(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002323 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002324 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002325 }
2326 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002327
Chris Lattner42790482007-12-20 01:56:58 +00002328 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002329 {
2330 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002331 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002332 if (!SI) {
2333 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002334 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002335 }
Chris Lattner42790482007-12-20 01:56:58 +00002336 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002337 Value *TV = SI->getTrueValue();
2338 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002339 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002340
2341 // Can we fold the add into the argument of the select?
2342 // We check both true and false select arguments for a matching subtract.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002343 if (match(FV, m_Zero(), *Context) &&
2344 match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002345 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002346 return SelectInst::Create(SI->getCondition(), N, A);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002347 if (match(TV, m_Zero(), *Context) &&
2348 match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002349 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002350 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002351 }
2352 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002353
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002354 // Check for (add (sext x), y), see if we can merge this into an
2355 // integer add followed by a sext.
2356 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2357 // (add (sext x), cst) --> (sext (add x, cst'))
2358 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2359 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002360 Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002361 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002362 Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002363 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2364 // Insert the new, smaller add.
2365 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2366 CI, "addconv");
2367 InsertNewInstBefore(NewAdd, I);
2368 return new SExtInst(NewAdd, I.getType());
2369 }
2370 }
2371
2372 // (add (sext x), (sext y)) --> (sext (add int x, y))
2373 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2374 // Only do this if x/y have the same type, if at last one of them has a
2375 // single use (so we don't increase the number of sexts), and if the
2376 // integer add will not overflow.
2377 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2378 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2379 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2380 RHSConv->getOperand(0))) {
2381 // Insert the new integer add.
2382 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2383 RHSConv->getOperand(0),
2384 "addconv");
2385 InsertNewInstBefore(NewAdd, I);
2386 return new SExtInst(NewAdd, I.getType());
2387 }
2388 }
2389 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002390
2391 return Changed ? &I : 0;
2392}
2393
2394Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2395 bool Changed = SimplifyCommutative(I);
2396 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2397
2398 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2399 // X + 0 --> X
2400 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002401 if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002402 (I.getType())->getValueAPF()))
2403 return ReplaceInstUsesWith(I, LHS);
2404 }
2405
2406 if (isa<PHINode>(LHS))
2407 if (Instruction *NV = FoldOpIntoPhi(I))
2408 return NV;
2409 }
2410
2411 // -A + B --> B - A
2412 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002413 if (Value *LHSV = dyn_castFNegVal(LHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002414 return BinaryOperator::CreateFSub(RHS, LHSV);
2415
2416 // A + -B --> A - B
2417 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002418 if (Value *V = dyn_castFNegVal(RHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002419 return BinaryOperator::CreateFSub(LHS, V);
2420
2421 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2422 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2423 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2424 return ReplaceInstUsesWith(I, LHS);
2425
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002426 // Check for (add double (sitofp x), y), see if we can merge this into an
2427 // integer add followed by a promotion.
2428 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2429 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2430 // ... if the constant fits in the integer value. This is useful for things
2431 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2432 // requires a constant pool load, and generally allows the add to be better
2433 // instcombined.
2434 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2435 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002436 Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002437 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002438 Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002439 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2440 // Insert the new integer add.
2441 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2442 CI, "addconv");
2443 InsertNewInstBefore(NewAdd, I);
2444 return new SIToFPInst(NewAdd, I.getType());
2445 }
2446 }
2447
2448 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2449 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2450 // Only do this if x/y have the same type, if at last one of them has a
2451 // single use (so we don't increase the number of int->fp conversions),
2452 // and if the integer add will not overflow.
2453 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2454 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2455 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2456 RHSConv->getOperand(0))) {
2457 // Insert the new integer add.
2458 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2459 RHSConv->getOperand(0),
2460 "addconv");
2461 InsertNewInstBefore(NewAdd, I);
2462 return new SIToFPInst(NewAdd, I.getType());
2463 }
2464 }
2465 }
2466
Chris Lattner7e708292002-06-25 16:13:24 +00002467 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002468}
2469
Chris Lattner7e708292002-06-25 16:13:24 +00002470Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002471 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002472
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002473 if (Op0 == Op1) // sub X, X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002474 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002475
Chris Lattner233f7dc2002-08-12 21:17:25 +00002476 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002477 if (Value *V = dyn_castNegVal(Op1, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002478 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002479
Chris Lattnere87597f2004-10-16 18:11:37 +00002480 if (isa<UndefValue>(Op0))
2481 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2482 if (isa<UndefValue>(Op1))
2483 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2484
Chris Lattnerd65460f2003-11-05 01:06:05 +00002485 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2486 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002487 if (C->isAllOnesValue())
Owen Anderson73c6b712009-07-13 20:58:05 +00002488 return BinaryOperator::CreateNot(*Context, Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002489
Chris Lattnerd65460f2003-11-05 01:06:05 +00002490 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002491 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002492 if (match(Op1, m_Not(m_Value(X)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002493 return BinaryOperator::CreateAdd(X, AddOne(C, Context));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002494
Chris Lattner76b7a062007-01-15 07:02:54 +00002495 // -(X >>u 31) -> (X >>s 31)
2496 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002497 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002498 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002499 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002500 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002501 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002502 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002503 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002504 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002505 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002506 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002507 }
2508 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002509 }
2510 else if (SI->getOpcode() == Instruction::AShr) {
2511 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2512 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002513 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002514 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002515 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002516 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002517 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002518 }
2519 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002520 }
2521 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002522 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002523
2524 // Try to fold constant sub into select arguments.
2525 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002526 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002527 return R;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002528 }
2529
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002530 if (I.getType() == Type::Int1Ty)
2531 return BinaryOperator::CreateXor(Op0, Op1);
2532
Chris Lattner43d84d62005-04-07 16:15:25 +00002533 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002534 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002535 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002536 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2537 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002538 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002539 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0),
2540 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002541 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2542 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2543 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002544 return BinaryOperator::CreateSub(
2545 Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002546 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002547 }
2548
Chris Lattnerfd059242003-10-15 16:48:29 +00002549 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002550 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2551 // is not used by anyone else...
2552 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002553 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002554 // Swap the two operands of the subexpr...
2555 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2556 Op1I->setOperand(0, IIOp1);
2557 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002558
Chris Lattnera2881962003-02-18 19:28:33 +00002559 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002560 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002561 }
2562
2563 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2564 //
2565 if (Op1I->getOpcode() == Instruction::And &&
2566 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2567 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2568
Chris Lattnerf523d062004-06-09 05:08:07 +00002569 Value *NewNot =
Owen Anderson73c6b712009-07-13 20:58:05 +00002570 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
2571 OtherOp, "B.not"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002572 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002573 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002574
Reid Spencerac5209e2006-10-16 23:08:08 +00002575 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002576 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002577 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002578 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002579 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002580 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002581 Context->getConstantExprNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002582
Chris Lattnerad3448c2003-02-18 19:57:07 +00002583 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002584 ConstantInt *C2 = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00002585 if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2586 Constant *CP1 =
2587 Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002588 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002589 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002590 }
Chris Lattner40371712002-05-09 01:29:19 +00002591 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002592 }
Chris Lattnera2881962003-02-18 19:28:33 +00002593
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002594 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2595 if (Op0I->getOpcode() == Instruction::Add) {
2596 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2597 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2598 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2599 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2600 } else if (Op0I->getOpcode() == Instruction::Sub) {
2601 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002602 return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2603 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002604 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002605 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002606
Chris Lattner50af16a2004-11-13 19:50:12 +00002607 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002608 if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002609 if (X == Op1) // X*C - X --> X * (C-1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002610 return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002611
Chris Lattner50af16a2004-11-13 19:50:12 +00002612 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Owen Andersond672ecb2009-07-03 00:17:18 +00002613 if (X == dyn_castFoldableMul(Op1, C2, Context))
2614 return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002615 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002616 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002617}
2618
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002619Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2620 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2621
2622 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002623 if (Value *V = dyn_castFNegVal(Op1, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002624 return BinaryOperator::CreateFAdd(Op0, V);
2625
2626 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2627 if (Op1I->getOpcode() == Instruction::FAdd) {
2628 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002629 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2630 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002631 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002632 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2633 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002634 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002635 }
2636
2637 return 0;
2638}
2639
Chris Lattnera0141b92007-07-15 20:42:37 +00002640/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2641/// comparison only checks the sign bit. If it only checks the sign bit, set
2642/// TrueIfSigned if the result of the comparison is true when the input value is
2643/// signed.
2644static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2645 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002646 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002647 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2648 TrueIfSigned = true;
2649 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002650 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2651 TrueIfSigned = true;
2652 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002653 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2654 TrueIfSigned = false;
2655 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002656 case ICmpInst::ICMP_UGT:
2657 // True if LHS u> RHS and RHS == high-bit-mask - 1
2658 TrueIfSigned = true;
2659 return RHS->getValue() ==
2660 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2661 case ICmpInst::ICMP_UGE:
2662 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2663 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002664 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002665 default:
2666 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002667 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002668}
2669
Chris Lattner7e708292002-06-25 16:13:24 +00002670Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002671 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002672 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002673
Dan Gohman77b81fe2009-06-04 17:12:12 +00002674 // TODO: If Op1 is undef and Op0 is finite, return zero.
2675 if (!I.getType()->isFPOrFPVector() &&
2676 isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002677 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002678
Chris Lattner233f7dc2002-08-12 21:17:25 +00002679 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002680 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2681 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002682
2683 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002684 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002685 if (SI->getOpcode() == Instruction::Shl)
2686 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002687 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002688 Context->getConstantExprShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002689
Zhou Sheng843f07672007-04-19 05:39:12 +00002690 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002691 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2692 if (CI->equalsInt(1)) // X * 1 == X
2693 return ReplaceInstUsesWith(I, Op0);
2694 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002695 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002696
Zhou Sheng97b52c22007-03-29 01:57:21 +00002697 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002698 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002699 return BinaryOperator::CreateShl(Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00002700 Context->getConstantInt(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002701 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002702 } else if (isa<VectorType>(Op1->getType())) {
Dan Gohman77b81fe2009-06-04 17:12:12 +00002703 // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
Nick Lewycky895f0852008-11-27 20:21:08 +00002704
2705 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2706 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002707 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002708
2709 // As above, vector X*splat(1.0) -> X in all defined cases.
2710 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002711 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2712 if (CI->equalsInt(1))
2713 return ReplaceInstUsesWith(I, Op0);
2714 }
2715 }
Chris Lattnera2881962003-02-18 19:28:33 +00002716 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002717
2718 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2719 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002720 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002721 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002722 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002723 Op1, "tmp");
2724 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00002725 Value *C1C2 = Context->getConstantExprMul(Op1,
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002726 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002727 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002728
2729 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002730
2731 // Try to fold constant mul into select arguments.
2732 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002733 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002734 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002735
2736 if (isa<PHINode>(Op0))
2737 if (Instruction *NV = FoldOpIntoPhi(I))
2738 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002739 }
2740
Owen Andersond672ecb2009-07-03 00:17:18 +00002741 if (Value *Op0v = dyn_castNegVal(Op0, Context)) // -X * -Y = X*Y
2742 if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002743 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002744
Nick Lewycky0c730792008-11-21 07:33:58 +00002745 // (X / Y) * Y = X - (X % Y)
2746 // (X / Y) * -Y = (X % Y) - X
2747 {
2748 Value *Op1 = I.getOperand(1);
2749 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2750 if (!BO ||
2751 (BO->getOpcode() != Instruction::UDiv &&
2752 BO->getOpcode() != Instruction::SDiv)) {
2753 Op1 = Op0;
2754 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2755 }
Owen Andersond672ecb2009-07-03 00:17:18 +00002756 Value *Neg = dyn_castNegVal(Op1, Context);
Nick Lewycky0c730792008-11-21 07:33:58 +00002757 if (BO && BO->hasOneUse() &&
2758 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2759 (BO->getOpcode() == Instruction::UDiv ||
2760 BO->getOpcode() == Instruction::SDiv)) {
2761 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2762
2763 Instruction *Rem;
2764 if (BO->getOpcode() == Instruction::UDiv)
2765 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2766 else
2767 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2768
2769 InsertNewInstBefore(Rem, I);
2770 Rem->takeName(BO);
2771
2772 if (Op1BO == Op1)
2773 return BinaryOperator::CreateSub(Op0BO, Rem);
2774 else
2775 return BinaryOperator::CreateSub(Rem, Op0BO);
2776 }
2777 }
2778
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002779 if (I.getType() == Type::Int1Ty)
2780 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2781
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002782 // If one of the operands of the multiply is a cast from a boolean value, then
2783 // we know the bool is either zero or one, so this is a 'masking' multiply.
2784 // See if we can simplify things based on how the boolean was originally
2785 // formed.
2786 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002787 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002788 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002789 BoolCast = CI;
2790 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002791 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002792 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002793 BoolCast = CI;
2794 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002795 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002796 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2797 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002798 bool TIS = false;
2799
Reid Spencere4d87aa2006-12-23 06:05:41 +00002800 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002801 // multiply into a shift/and combination.
2802 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002803 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2804 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002805 // Shift the X value right to turn it into "all signbits".
Owen Andersond672ecb2009-07-03 00:17:18 +00002806 Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002807 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002808 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002809 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002810 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002811 BoolCast->getOperand(0)->getName()+
2812 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002813
2814 // If the multiply type is not the same as the source type, sign extend
2815 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002816 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002817 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2818 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002819 Instruction::CastOps opcode =
2820 (SrcBits == DstBits ? Instruction::BitCast :
2821 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2822 V = InsertCastBefore(opcode, V, I.getType(), I);
2823 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002824
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002825 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002826 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002827 }
2828 }
2829 }
2830
Chris Lattner7e708292002-06-25 16:13:24 +00002831 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002832}
2833
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002834Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2835 bool Changed = SimplifyCommutative(I);
2836 Value *Op0 = I.getOperand(0);
2837
2838 // Simplify mul instructions with a constant RHS...
2839 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2840 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2841 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2842 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2843 if (Op1F->isExactlyValue(1.0))
2844 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2845 } else if (isa<VectorType>(Op1->getType())) {
2846 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2847 // As above, vector X*splat(1.0) -> X in all defined cases.
2848 if (Constant *Splat = Op1V->getSplatValue()) {
2849 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2850 if (F->isExactlyValue(1.0))
2851 return ReplaceInstUsesWith(I, Op0);
2852 }
2853 }
2854 }
2855
2856 // Try to fold constant mul into select arguments.
2857 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2858 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2859 return R;
2860
2861 if (isa<PHINode>(Op0))
2862 if (Instruction *NV = FoldOpIntoPhi(I))
2863 return NV;
2864 }
2865
Owen Andersond672ecb2009-07-03 00:17:18 +00002866 if (Value *Op0v = dyn_castFNegVal(Op0, Context)) // -X * -Y = X*Y
2867 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002868 return BinaryOperator::CreateFMul(Op0v, Op1v);
2869
2870 return Changed ? &I : 0;
2871}
2872
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002873/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2874/// instruction.
2875bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2876 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2877
2878 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2879 int NonNullOperand = -1;
2880 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2881 if (ST->isNullValue())
2882 NonNullOperand = 2;
2883 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2884 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2885 if (ST->isNullValue())
2886 NonNullOperand = 1;
2887
2888 if (NonNullOperand == -1)
2889 return false;
2890
2891 Value *SelectCond = SI->getOperand(0);
2892
2893 // Change the div/rem to use 'Y' instead of the select.
2894 I.setOperand(1, SI->getOperand(NonNullOperand));
2895
2896 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2897 // problem. However, the select, or the condition of the select may have
2898 // multiple uses. Based on our knowledge that the operand must be non-zero,
2899 // propagate the known value for the select into other uses of it, and
2900 // propagate a known value of the condition into its other users.
2901
2902 // If the select and condition only have a single use, don't bother with this,
2903 // early exit.
2904 if (SI->use_empty() && SelectCond->hasOneUse())
2905 return true;
2906
2907 // Scan the current block backward, looking for other uses of SI.
2908 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2909
2910 while (BBI != BBFront) {
2911 --BBI;
2912 // If we found a call to a function, we can't assume it will return, so
2913 // information from below it cannot be propagated above it.
2914 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2915 break;
2916
2917 // Replace uses of the select or its condition with the known values.
2918 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2919 I != E; ++I) {
2920 if (*I == SI) {
2921 *I = SI->getOperand(NonNullOperand);
2922 AddToWorkList(BBI);
2923 } else if (*I == SelectCond) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002924 *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2925 Context->getConstantIntFalse();
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002926 AddToWorkList(BBI);
2927 }
2928 }
2929
2930 // If we past the instruction, quit looking for it.
2931 if (&*BBI == SI)
2932 SI = 0;
2933 if (&*BBI == SelectCond)
2934 SelectCond = 0;
2935
2936 // If we ran out of things to eliminate, break out of the loop.
2937 if (SelectCond == 0 && SI == 0)
2938 break;
2939
2940 }
2941 return true;
2942}
2943
2944
Reid Spencer1628cec2006-10-26 06:15:43 +00002945/// This function implements the transforms on div instructions that work
2946/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2947/// used by the visitors to those instructions.
2948/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002949Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002950 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002951
Chris Lattner50b2ca42008-02-19 06:12:18 +00002952 // undef / X -> 0 for integer.
2953 // undef / X -> undef for FP (the undef could be a snan).
2954 if (isa<UndefValue>(Op0)) {
2955 if (Op0->getType()->isFPOrFPVector())
2956 return ReplaceInstUsesWith(I, Op0);
Owen Andersond672ecb2009-07-03 00:17:18 +00002957 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002958 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002959
2960 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002961 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002962 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002963
Reid Spencer1628cec2006-10-26 06:15:43 +00002964 return 0;
2965}
Misha Brukmanfd939082005-04-21 23:48:37 +00002966
Reid Spencer1628cec2006-10-26 06:15:43 +00002967/// This function implements the transforms common to both integer division
2968/// instructions (udiv and sdiv). It is called by the visitors to those integer
2969/// division instructions.
2970/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002971Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002972 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2973
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002974 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002975 if (Op0 == Op1) {
2976 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002977 Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002978 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00002979 return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002980 }
2981
Owen Andersond672ecb2009-07-03 00:17:18 +00002982 Constant *CI = Context->getConstantInt(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002983 return ReplaceInstUsesWith(I, CI);
2984 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002985
Reid Spencer1628cec2006-10-26 06:15:43 +00002986 if (Instruction *Common = commonDivTransforms(I))
2987 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002988
2989 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2990 // This does not apply for fdiv.
2991 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2992 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002993
2994 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2995 // div X, 1 == X
2996 if (RHS->equalsInt(1))
2997 return ReplaceInstUsesWith(I, Op0);
2998
2999 // (X / C1) / C2 -> X / (C1*C2)
3000 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3001 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3002 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003003 if (MultiplyOverflows(RHS, LHSRHS,
3004 I.getOpcode()==Instruction::SDiv, Context))
3005 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003006 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003007 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00003008 Context->getConstantExprMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003009 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003010
Reid Spencerbca0e382007-03-23 20:05:17 +00003011 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003012 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3013 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3014 return R;
3015 if (isa<PHINode>(Op0))
3016 if (Instruction *NV = FoldOpIntoPhi(I))
3017 return NV;
3018 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003019 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003020
Chris Lattnera2881962003-02-18 19:28:33 +00003021 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003022 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003023 if (LHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00003024 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003025
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003026 // It can't be division by zero, hence it must be division by one.
3027 if (I.getType() == Type::Int1Ty)
3028 return ReplaceInstUsesWith(I, Op0);
3029
Nick Lewycky895f0852008-11-27 20:21:08 +00003030 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3031 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3032 // div X, 1 == X
3033 if (X->isOne())
3034 return ReplaceInstUsesWith(I, Op0);
3035 }
3036
Reid Spencer1628cec2006-10-26 06:15:43 +00003037 return 0;
3038}
3039
3040Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3041 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3042
3043 // Handle the integer div common cases
3044 if (Instruction *Common = commonIDivTransforms(I))
3045 return Common;
3046
Reid Spencer1628cec2006-10-26 06:15:43 +00003047 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003048 // X udiv C^2 -> X >> C
3049 // Check to see if this is an unsigned division with an exact power of 2,
3050 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003051 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003052 return BinaryOperator::CreateLShr(Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00003053 Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003054
3055 // X udiv C, where C >= signbit
3056 if (C->getValue().isNegative()) {
Owen Anderson333c4002009-07-09 23:48:35 +00003057 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3058 ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky8ca52482008-11-27 22:41:10 +00003059 I);
Owen Andersond672ecb2009-07-03 00:17:18 +00003060 return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3061 Context->getConstantInt(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003062 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003063 }
3064
3065 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003066 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003067 if (RHSI->getOpcode() == Instruction::Shl &&
3068 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003069 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003070 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003071 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003072 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003073 if (uint32_t C2 = C1.logBase2()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003074 Constant *C2V = Context->getConstantInt(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003075 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003076 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003077 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003078 }
3079 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003080 }
3081
Reid Spencer1628cec2006-10-26 06:15:43 +00003082 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3083 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003084 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003085 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003086 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003087 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003088 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003089 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003090 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003091 // Construct the "on true" case of the select
Owen Andersond672ecb2009-07-03 00:17:18 +00003092 Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003093 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003094 Op0, TC, SI->getName()+".t");
3095 TSI = InsertNewInstBefore(TSI, I);
3096
3097 // Construct the "on false" case of the select
Owen Andersond672ecb2009-07-03 00:17:18 +00003098 Constant *FC = Context->getConstantInt(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003099 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003100 Op0, FC, SI->getName()+".f");
3101 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003102
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003103 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003104 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003105 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003106 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003107 return 0;
3108}
3109
Reid Spencer1628cec2006-10-26 06:15:43 +00003110Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3111 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3112
3113 // Handle the integer div common cases
3114 if (Instruction *Common = commonIDivTransforms(I))
3115 return Common;
3116
3117 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3118 // sdiv X, -1 == -X
3119 if (RHS->isAllOnesValue())
Owen Anderson0a5372e2009-07-13 04:09:18 +00003120 return BinaryOperator::CreateNeg(*Context, Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003121 }
3122
3123 // If the sign bits of both operands are zero (i.e. we can prove they are
3124 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003125 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003126 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003127 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003128 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003129 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003130 }
3131 }
3132
3133 return 0;
3134}
3135
3136Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3137 return commonDivTransforms(I);
3138}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003139
Reid Spencer0a783f72006-11-02 01:53:59 +00003140/// This function implements the transforms on rem instructions that work
3141/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3142/// is used by the visitors to those instructions.
3143/// @brief Transforms common to all three rem instructions
3144Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003145 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003146
Chris Lattner50b2ca42008-02-19 06:12:18 +00003147 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3148 if (I.getType()->isFPOrFPVector())
3149 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersond672ecb2009-07-03 00:17:18 +00003150 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003151 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003152 if (isa<UndefValue>(Op1))
3153 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003154
3155 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003156 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3157 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003158
Reid Spencer0a783f72006-11-02 01:53:59 +00003159 return 0;
3160}
3161
3162/// This function implements the transforms common to both integer remainder
3163/// instructions (urem and srem). It is called by the visitors to those integer
3164/// remainder instructions.
3165/// @brief Common integer remainder transforms
3166Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3167 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3168
3169 if (Instruction *common = commonRemTransforms(I))
3170 return common;
3171
Dale Johannesened6af242009-01-21 00:35:19 +00003172 // 0 % X == 0 for integer, we don't need to preserve faults!
3173 if (Constant *LHS = dyn_cast<Constant>(Op0))
3174 if (LHS->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00003175 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003176
Chris Lattner857e8cd2004-12-12 21:48:58 +00003177 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003178 // X % 0 == undef, we don't need to preserve faults!
3179 if (RHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00003180 return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003181
Chris Lattnera2881962003-02-18 19:28:33 +00003182 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003183 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003184
Chris Lattner97943922006-02-28 05:49:21 +00003185 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3186 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3187 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3188 return R;
3189 } else if (isa<PHINode>(Op0I)) {
3190 if (Instruction *NV = FoldOpIntoPhi(I))
3191 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003192 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003193
3194 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003195 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003196 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003197 }
Chris Lattnera2881962003-02-18 19:28:33 +00003198 }
3199
Reid Spencer0a783f72006-11-02 01:53:59 +00003200 return 0;
3201}
3202
3203Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3204 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3205
3206 if (Instruction *common = commonIRemTransforms(I))
3207 return common;
3208
3209 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3210 // X urem C^2 -> X and C
3211 // Check to see if this is an unsigned remainder with an exact power of 2,
3212 // if so, convert to a bitwise and.
3213 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003214 if (C->getValue().isPowerOf2())
Owen Andersond672ecb2009-07-03 00:17:18 +00003215 return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
Reid Spencer0a783f72006-11-02 01:53:59 +00003216 }
3217
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003218 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003219 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3220 if (RHSI->getOpcode() == Instruction::Shl &&
3221 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003222 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Anderson73c6b712009-07-13 20:58:05 +00003223 Constant *N1 = Context->getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003224 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003225 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003226 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003227 }
3228 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003229 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003230
Reid Spencer0a783f72006-11-02 01:53:59 +00003231 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3232 // where C1&C2 are powers of two.
3233 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3234 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3235 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3236 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003237 if ((STO->getValue().isPowerOf2()) &&
3238 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003239 Value *TrueAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003240 BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3241 SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003242 Value *FalseAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003243 BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3244 SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003245 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003246 }
3247 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003248 }
3249
Chris Lattner3f5b8772002-05-06 16:14:14 +00003250 return 0;
3251}
3252
Reid Spencer0a783f72006-11-02 01:53:59 +00003253Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3254 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3255
Dan Gohmancff55092007-11-05 23:16:33 +00003256 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003257 if (Instruction *common = commonIRemTransforms(I))
3258 return common;
3259
Owen Andersond672ecb2009-07-03 00:17:18 +00003260 if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
Nick Lewycky23c04302008-09-03 06:24:21 +00003261 if (!isa<Constant>(RHSNeg) ||
3262 (isa<ConstantInt>(RHSNeg) &&
3263 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003264 // X % -Y -> X % Y
3265 AddUsesToWorkList(I);
3266 I.setOperand(1, RHSNeg);
3267 return &I;
3268 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003269
Dan Gohmancff55092007-11-05 23:16:33 +00003270 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003271 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003272 if (I.getType()->isInteger()) {
3273 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3274 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3275 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003276 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003277 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003278 }
3279
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003280 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003281 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3282 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003283
Nick Lewycky9dce8732008-12-20 16:48:00 +00003284 bool hasNegative = false;
3285 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3286 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3287 if (RHS->getValue().isNegative())
3288 hasNegative = true;
3289
3290 if (hasNegative) {
3291 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003292 for (unsigned i = 0; i != VWidth; ++i) {
3293 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3294 if (RHS->getValue().isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00003295 Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003296 else
3297 Elts[i] = RHS;
3298 }
3299 }
3300
Owen Andersond672ecb2009-07-03 00:17:18 +00003301 Constant *NewRHSV = Context->getConstantVector(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003302 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003303 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003304 I.setOperand(1, NewRHSV);
3305 return &I;
3306 }
3307 }
3308 }
3309
Reid Spencer0a783f72006-11-02 01:53:59 +00003310 return 0;
3311}
3312
3313Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003314 return commonRemTransforms(I);
3315}
3316
Chris Lattner457dd822004-06-09 07:59:58 +00003317// isOneBitSet - Return true if there is exactly one bit set in the specified
3318// constant.
3319static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003320 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003321}
3322
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003323// isHighOnes - Return true if the constant is of the form 1+0+.
3324// This is the same as lowones(~X).
3325static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003326 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003327}
3328
Reid Spencere4d87aa2006-12-23 06:05:41 +00003329/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003330/// are carefully arranged to allow folding of expressions such as:
3331///
3332/// (A < B) | (A > B) --> (A != B)
3333///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003334/// Note that this is only valid if the first and second predicates have the
3335/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003336///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003337/// Three bits are used to represent the condition, as follows:
3338/// 0 A > B
3339/// 1 A == B
3340/// 2 A < B
3341///
3342/// <=> Value Definition
3343/// 000 0 Always false
3344/// 001 1 A > B
3345/// 010 2 A == B
3346/// 011 3 A >= B
3347/// 100 4 A < B
3348/// 101 5 A != B
3349/// 110 6 A <= B
3350/// 111 7 Always true
3351///
3352static unsigned getICmpCode(const ICmpInst *ICI) {
3353 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003354 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003355 case ICmpInst::ICMP_UGT: return 1; // 001
3356 case ICmpInst::ICMP_SGT: return 1; // 001
3357 case ICmpInst::ICMP_EQ: return 2; // 010
3358 case ICmpInst::ICMP_UGE: return 3; // 011
3359 case ICmpInst::ICMP_SGE: return 3; // 011
3360 case ICmpInst::ICMP_ULT: return 4; // 100
3361 case ICmpInst::ICMP_SLT: return 4; // 100
3362 case ICmpInst::ICMP_NE: return 5; // 101
3363 case ICmpInst::ICMP_ULE: return 6; // 110
3364 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003365 // True -> 7
3366 default:
Torok Edwinc25e7582009-07-11 20:10:48 +00003367 LLVM_UNREACHABLE("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003368 return 0;
3369 }
3370}
3371
Evan Cheng8db90722008-10-14 17:15:11 +00003372/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3373/// predicate into a three bit mask. It also returns whether it is an ordered
3374/// predicate by reference.
3375static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3376 isOrdered = false;
3377 switch (CC) {
3378 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3379 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003380 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3381 case FCmpInst::FCMP_UGT: return 1; // 001
3382 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3383 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003384 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3385 case FCmpInst::FCMP_UGE: return 3; // 011
3386 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3387 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003388 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3389 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003390 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3391 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003392 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003393 default:
3394 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc25e7582009-07-11 20:10:48 +00003395 LLVM_UNREACHABLE("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003396 return 0;
3397 }
3398}
3399
Reid Spencere4d87aa2006-12-23 06:05:41 +00003400/// getICmpValue - This is the complement of getICmpCode, which turns an
3401/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003402/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003403/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003404static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003405 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003406 switch (code) {
Torok Edwinc25e7582009-07-11 20:10:48 +00003407 default: LLVM_UNREACHABLE("Illegal ICmp code!");
Owen Andersond672ecb2009-07-03 00:17:18 +00003408 case 0: return Context->getConstantIntFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003409 case 1:
3410 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003411 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003412 else
Owen Anderson333c4002009-07-09 23:48:35 +00003413 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3414 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003415 case 3:
3416 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003417 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003418 else
Owen Anderson333c4002009-07-09 23:48:35 +00003419 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003420 case 4:
3421 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003422 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003423 else
Owen Anderson333c4002009-07-09 23:48:35 +00003424 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3425 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003426 case 6:
3427 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003428 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003429 else
Owen Anderson333c4002009-07-09 23:48:35 +00003430 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00003431 case 7: return Context->getConstantIntTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003432 }
3433}
3434
Evan Cheng8db90722008-10-14 17:15:11 +00003435/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3436/// opcode and two operands into either a FCmp instruction. isordered is passed
3437/// in to determine which kind of predicate to use in the new fcmp instruction.
3438static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003439 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003440 switch (code) {
Torok Edwinc25e7582009-07-11 20:10:48 +00003441 default: LLVM_UNREACHABLE("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003442 case 0:
3443 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003444 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003445 else
Owen Anderson333c4002009-07-09 23:48:35 +00003446 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003447 case 1:
3448 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003449 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003450 else
Owen Anderson333c4002009-07-09 23:48:35 +00003451 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003452 case 2:
3453 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003454 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003455 else
Owen Anderson333c4002009-07-09 23:48:35 +00003456 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003457 case 3:
3458 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003459 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003460 else
Owen Anderson333c4002009-07-09 23:48:35 +00003461 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003462 case 4:
3463 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003464 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003465 else
Owen Anderson333c4002009-07-09 23:48:35 +00003466 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003467 case 5:
3468 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003469 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003470 else
Owen Anderson333c4002009-07-09 23:48:35 +00003471 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003472 case 6:
3473 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003474 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003475 else
Owen Anderson333c4002009-07-09 23:48:35 +00003476 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00003477 case 7: return Context->getConstantIntTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003478 }
3479}
3480
Chris Lattnerb9553d62008-11-16 04:55:20 +00003481/// PredicatesFoldable - Return true if both predicates match sign or if at
3482/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003483static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3484 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003485 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3486 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003487}
3488
3489namespace {
3490// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3491struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003492 InstCombiner &IC;
3493 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003494 ICmpInst::Predicate pred;
3495 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3496 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3497 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003498 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003499 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3500 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003501 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3502 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003503 return false;
3504 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003505 Instruction *apply(Instruction &Log) const {
3506 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3507 if (ICI->getOperand(0) != LHS) {
3508 assert(ICI->getOperand(1) == LHS);
3509 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003510 }
3511
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003512 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003513 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003514 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003515 unsigned Code;
3516 switch (Log.getOpcode()) {
3517 case Instruction::And: Code = LHSCode & RHSCode; break;
3518 case Instruction::Or: Code = LHSCode | RHSCode; break;
3519 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc25e7582009-07-11 20:10:48 +00003520 default: LLVM_UNREACHABLE("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003521 }
3522
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003523 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3524 ICmpInst::isSignedPredicate(ICI->getPredicate());
3525
Owen Andersond672ecb2009-07-03 00:17:18 +00003526 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003527 if (Instruction *I = dyn_cast<Instruction>(RV))
3528 return I;
3529 // Otherwise, it's a constant boolean value...
3530 return IC.ReplaceInstUsesWith(Log, RV);
3531 }
3532};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003533} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003534
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003535// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3536// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003537// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003538Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003539 ConstantInt *OpRHS,
3540 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003541 BinaryOperator &TheAnd) {
3542 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003543 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003544 if (!Op->isShift())
Owen Andersond672ecb2009-07-03 00:17:18 +00003545 Together = Context->getConstantExprAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003546
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003547 switch (Op->getOpcode()) {
3548 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003549 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003550 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003551 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003552 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003553 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003554 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003555 }
3556 break;
3557 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003558 if (Together == AndRHS) // (X | C) & C --> C
3559 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003560
Chris Lattner6e7ba452005-01-01 16:22:27 +00003561 if (Op->hasOneUse() && Together != OpRHS) {
3562 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003563 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003564 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003565 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003566 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003567 }
3568 break;
3569 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003570 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003571 // Adding a one to a single bit bit-field should be turned into an XOR
3572 // of the bit. First thing to check is to see if this AND is with a
3573 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003574 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003575
3576 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003577 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003578 // Ok, at this point, we know that we are masking the result of the
3579 // ADD down to exactly one bit. If the constant we are adding has
3580 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003581 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003582
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003583 // Check to see if any bits below the one bit set in AndRHSV are set.
3584 if ((AddRHS & (AndRHSV-1)) == 0) {
3585 // If not, the only thing that can effect the output of the AND is
3586 // the bit specified by AndRHSV. If that bit is set, the effect of
3587 // the XOR is to toggle the bit. If it is clear, then the ADD has
3588 // no effect.
3589 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3590 TheAnd.setOperand(0, X);
3591 return &TheAnd;
3592 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003593 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003594 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003595 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003596 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003597 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003598 }
3599 }
3600 }
3601 }
3602 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003603
3604 case Instruction::Shl: {
3605 // We know that the AND will not produce any of the bits shifted in, so if
3606 // the anded constant includes them, clear them now!
3607 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003608 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003609 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003610 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003611 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003612
Zhou Sheng290bec52007-03-29 08:15:12 +00003613 if (CI->getValue() == ShlMask) {
3614 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003615 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3616 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003617 TheAnd.setOperand(1, CI);
3618 return &TheAnd;
3619 }
3620 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003621 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003622 case Instruction::LShr:
3623 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003624 // We know that the AND will not produce any of the bits shifted in, so if
3625 // the anded constant includes them, clear them now! This only applies to
3626 // unsigned shifts, because a signed shr may bring in set bits!
3627 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003628 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003629 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003630 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003631 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003632
Zhou Sheng290bec52007-03-29 08:15:12 +00003633 if (CI->getValue() == ShrMask) {
3634 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003635 return ReplaceInstUsesWith(TheAnd, Op);
3636 } else if (CI != AndRHS) {
3637 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3638 return &TheAnd;
3639 }
3640 break;
3641 }
3642 case Instruction::AShr:
3643 // Signed shr.
3644 // See if this is shifting in some sign extension, then masking it out
3645 // with an and.
3646 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003647 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003648 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003649 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003650 Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003651 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003652 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003653 // Make the argument unsigned.
3654 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003655 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003656 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003657 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003658 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003659 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003660 }
3661 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003662 }
3663 return 0;
3664}
3665
Chris Lattner8b170942002-08-09 23:47:40 +00003666
Chris Lattnera96879a2004-09-29 17:40:11 +00003667/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3668/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003669/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3670/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003671/// insert new instructions.
3672Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003673 bool isSigned, bool Inside,
3674 Instruction &IB) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003675 assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003676 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003677 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003678
Chris Lattnera96879a2004-09-29 17:40:11 +00003679 if (Inside) {
3680 if (Lo == Hi) // Trivially false.
Owen Anderson333c4002009-07-09 23:48:35 +00003681 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003682
Reid Spencere4d87aa2006-12-23 06:05:41 +00003683 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003684 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003685 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003686 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Owen Anderson333c4002009-07-09 23:48:35 +00003687 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003688 }
3689
3690 // Emit V-Lo <u Hi-Lo
Owen Andersond672ecb2009-07-03 00:17:18 +00003691 Constant *NegLo = Context->getConstantExprNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003692 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003693 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003694 Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003695 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003696 }
3697
3698 if (Lo == Hi) // Trivially true.
Owen Anderson333c4002009-07-09 23:48:35 +00003699 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003700
Reid Spencere4e40032007-03-21 23:19:50 +00003701 // V < Min || V >= Hi -> V > Hi-1
Owen Andersond672ecb2009-07-03 00:17:18 +00003702 Hi = SubOne(cast<ConstantInt>(Hi), Context);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003703 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003704 ICmpInst::Predicate pred = (isSigned ?
3705 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Owen Anderson333c4002009-07-09 23:48:35 +00003706 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003707 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003708
Reid Spencere4e40032007-03-21 23:19:50 +00003709 // Emit V-Lo >u Hi-1-Lo
3710 // Note that Hi has already had one subtracted from it, above.
Owen Andersond672ecb2009-07-03 00:17:18 +00003711 ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003712 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003713 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003714 Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003715 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003716}
3717
Chris Lattner7203e152005-09-18 07:22:02 +00003718// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3719// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3720// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3721// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003722static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003723 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003724 uint32_t BitWidth = Val->getType()->getBitWidth();
3725 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003726
3727 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003728 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003729 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003730 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003731 return true;
3732}
3733
Chris Lattner7203e152005-09-18 07:22:02 +00003734/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3735/// where isSub determines whether the operator is a sub. If we can fold one of
3736/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003737///
3738/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3739/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3740/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3741///
3742/// return (A +/- B).
3743///
3744Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003745 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003746 Instruction &I) {
3747 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3748 if (!LHSI || LHSI->getNumOperands() != 2 ||
3749 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3750
3751 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3752
3753 switch (LHSI->getOpcode()) {
3754 default: return 0;
3755 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00003756 if (Context->getConstantExprAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003757 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003758 if ((Mask->getValue().countLeadingZeros() +
3759 Mask->getValue().countPopulation()) ==
3760 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003761 break;
3762
3763 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3764 // part, we don't need any explicit masks to take them out of A. If that
3765 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003766 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003767 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003768 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003769 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003770 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003771 break;
3772 }
3773 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003774 return 0;
3775 case Instruction::Or:
3776 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003777 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003778 if ((Mask->getValue().countLeadingZeros() +
3779 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersond672ecb2009-07-03 00:17:18 +00003780 && Context->getConstantExprAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003781 break;
3782 return 0;
3783 }
3784
3785 Instruction *New;
3786 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003787 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003788 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003789 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003790 return InsertNewInstBefore(New, I);
3791}
3792
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003793/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3794Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3795 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003796 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003797 ConstantInt *LHSCst, *RHSCst;
3798 ICmpInst::Predicate LHSCC, RHSCC;
3799
Chris Lattnerea065fb2008-11-16 05:10:52 +00003800 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003801 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3802 m_ConstantInt(LHSCst)), *Context) ||
3803 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3804 m_ConstantInt(RHSCst)), *Context))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003805 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003806
3807 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3808 // where C is a power of 2
3809 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3810 LHSCst->getValue().isPowerOf2()) {
3811 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3812 InsertNewInstBefore(NewOr, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003813 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003814 }
3815
3816 // From here on, we only handle:
3817 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3818 if (Val != Val2) return 0;
3819
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003820 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3821 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3822 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3823 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3824 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3825 return 0;
3826
3827 // We can't fold (ugt x, C) & (sgt x, C2).
3828 if (!PredicatesFoldable(LHSCC, RHSCC))
3829 return 0;
3830
3831 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003832 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003833 if (ICmpInst::isSignedPredicate(LHSCC) ||
3834 (ICmpInst::isEquality(LHSCC) &&
3835 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003836 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003837 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003838 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3839
3840 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003841 std::swap(LHS, RHS);
3842 std::swap(LHSCst, RHSCst);
3843 std::swap(LHSCC, RHSCC);
3844 }
3845
3846 // At this point, we know we have have two icmp instructions
3847 // comparing a value against two constants and and'ing the result
3848 // together. Because of the above check, we know that we only have
3849 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3850 // (from the FoldICmpLogical check above), that the two constants
3851 // are not equal and that the larger constant is on the RHS
3852 assert(LHSCst != RHSCst && "Compares not folded above?");
3853
3854 switch (LHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00003855 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003856 case ICmpInst::ICMP_EQ:
3857 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00003858 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003859 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3860 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3861 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Andersond672ecb2009-07-03 00:17:18 +00003862 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003863 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3864 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3865 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3866 return ReplaceInstUsesWith(I, LHS);
3867 }
3868 case ICmpInst::ICMP_NE:
3869 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00003870 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003871 case ICmpInst::ICMP_ULT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003872 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003873 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003874 break; // (X != 13 & X u< 15) -> no change
3875 case ICmpInst::ICMP_SLT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003876 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003877 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003878 break; // (X != 13 & X s< 15) -> no change
3879 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3880 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3881 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3882 return ReplaceInstUsesWith(I, RHS);
3883 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003884 if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3885 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003886 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3887 Val->getName()+".off");
3888 InsertNewInstBefore(Add, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003889 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
Owen Andersond672ecb2009-07-03 00:17:18 +00003890 Context->getConstantInt(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003891 }
3892 break; // (X != 13 & X != 15) -> no change
3893 }
3894 break;
3895 case ICmpInst::ICMP_ULT:
3896 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00003897 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003898 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3899 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Andersond672ecb2009-07-03 00:17:18 +00003900 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003901 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3902 break;
3903 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3904 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3905 return ReplaceInstUsesWith(I, LHS);
3906 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3907 break;
3908 }
3909 break;
3910 case ICmpInst::ICMP_SLT:
3911 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00003912 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003913 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3914 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Andersond672ecb2009-07-03 00:17:18 +00003915 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003916 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3917 break;
3918 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3919 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3920 return ReplaceInstUsesWith(I, LHS);
3921 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3922 break;
3923 }
3924 break;
3925 case ICmpInst::ICMP_UGT:
3926 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00003927 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003928 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3929 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3930 return ReplaceInstUsesWith(I, RHS);
3931 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3932 break;
3933 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003934 if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003935 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003936 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003937 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003938 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3939 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003940 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3941 break;
3942 }
3943 break;
3944 case ICmpInst::ICMP_SGT:
3945 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00003946 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003947 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3948 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3949 return ReplaceInstUsesWith(I, RHS);
3950 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3951 break;
3952 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003953 if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003954 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003955 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003956 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003957 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3958 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003959 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3960 break;
3961 }
3962 break;
3963 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003964
3965 return 0;
3966}
3967
3968
Chris Lattner7e708292002-06-25 16:13:24 +00003969Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003970 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003971 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003972
Chris Lattnere87597f2004-10-16 18:11:37 +00003973 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003974 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003975
Chris Lattner6e7ba452005-01-01 16:22:27 +00003976 // and X, X = X
3977 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003978 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003979
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003980 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003981 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00003982 if (SimplifyDemandedInstructionBits(I))
3983 return &I;
3984 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003985 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003986 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003987 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003988 } else if (isa<ConstantAggregateZero>(Op1)) {
3989 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003990 }
3991 }
Dan Gohman6de29f82009-06-15 22:12:54 +00003992
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003993 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003994 const APInt& AndRHSMask = AndRHS->getValue();
3995 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003996
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003997 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003998 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003999 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004000 Value *Op0LHS = Op0I->getOperand(0);
4001 Value *Op0RHS = Op0I->getOperand(1);
4002 switch (Op0I->getOpcode()) {
4003 case Instruction::Xor:
4004 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004005 // If the mask is only needed on one incoming arm, push it up.
4006 if (Op0I->hasOneUse()) {
4007 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4008 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004009 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004010 Op0RHS->getName()+".masked");
4011 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004012 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004013 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004014 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004015 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004016 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4017 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004018 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004019 Op0LHS->getName()+".masked");
4020 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004021 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004022 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4023 }
4024 }
4025
Chris Lattner6e7ba452005-01-01 16:22:27 +00004026 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004027 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004028 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4029 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4030 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4031 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004032 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004033 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004034 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004035 break;
4036
4037 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004038 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4039 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4040 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4041 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004042 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004043
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004044 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4045 // has 1's for all bits that the subtraction with A might affect.
4046 if (Op0I->hasOneUse()) {
4047 uint32_t BitWidth = AndRHSMask.getBitWidth();
4048 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4049 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4050
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004051 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004052 if (!(A && A->isZero()) && // avoid infinite recursion.
4053 MaskedValueIsZero(Op0LHS, Mask)) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00004054 Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004055 InsertNewInstBefore(NewNeg, I);
4056 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4057 }
4058 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004059 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004060
4061 case Instruction::Shl:
4062 case Instruction::LShr:
4063 // (1 << x) & 1 --> zext(x == 0)
4064 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004065 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Owen Anderson333c4002009-07-09 23:48:35 +00004066 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4067 Op0RHS, Context->getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004068 InsertNewInstBefore(NewICmp, I);
4069 return new ZExtInst(NewICmp, I.getType());
4070 }
4071 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004072 }
4073
Chris Lattner58403262003-07-23 19:25:52 +00004074 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004075 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004076 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004077 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004078 // If this is an integer truncation or change from signed-to-unsigned, and
4079 // if the source is an and/or with immediate, transform it. This
4080 // frequently occurs for bitfield accesses.
4081 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004082 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004083 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004084 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004085 if (CastOp->getOpcode() == Instruction::And) {
4086 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004087 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4088 // This will fold the two constants together, which may allow
4089 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004090 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004091 CastOp->getOperand(0), I.getType(),
4092 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004093 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004094 // trunc_or_bitcast(C1)&C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004095 Constant *C3 =
4096 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4097 C3 = Context->getConstantExprAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004098 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004099 } else if (CastOp->getOpcode() == Instruction::Or) {
4100 // Change: and (cast (or X, C1) to T), C2
4101 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004102 Constant *C3 =
4103 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4104 if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4105 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004106 return ReplaceInstUsesWith(I, AndRHS);
4107 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004108 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004109 }
Chris Lattner06782f82003-07-23 19:36:21 +00004110 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004111
4112 // Try to fold constant and into select arguments.
4113 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004114 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004115 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004116 if (isa<PHINode>(Op0))
4117 if (Instruction *NV = FoldOpIntoPhi(I))
4118 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004119 }
4120
Owen Andersond672ecb2009-07-03 00:17:18 +00004121 Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4122 Value *Op1NotVal = dyn_castNotVal(Op1, Context);
Chris Lattnera2881962003-02-18 19:28:33 +00004123
Chris Lattner5b62aa72004-06-18 06:07:51 +00004124 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00004125 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004126
Misha Brukmancb6267b2004-07-30 12:50:08 +00004127 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004128 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004129 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004130 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004131 InsertNewInstBefore(Or, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004132 return BinaryOperator::CreateNot(*Context, Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004133 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004134
4135 {
Chris Lattner003b6202007-06-15 05:58:24 +00004136 Value *A = 0, *B = 0, *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004137 if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004138 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4139 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004140
4141 // (A|B) & ~(A&B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004142 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004143 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004144 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004145 }
4146 }
4147
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004148 if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004149 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4150 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004151
4152 // ~(A&B) & (A|B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004153 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004154 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004155 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004156 }
4157 }
Chris Lattner64daab52006-04-01 08:03:55 +00004158
4159 if (Op0->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004160 match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004161 if (A == Op1) { // (A^B)&A -> A&(A^B)
4162 I.swapOperands(); // Simplify below
4163 std::swap(Op0, Op1);
4164 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4165 cast<BinaryOperator>(Op0)->swapOperands();
4166 I.swapOperands(); // Simplify below
4167 std::swap(Op0, Op1);
4168 }
4169 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004170
Chris Lattner64daab52006-04-01 08:03:55 +00004171 if (Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004172 match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004173 if (B == Op0) { // B&(A^B) -> B&(B^A)
4174 cast<BinaryOperator>(Op1)->swapOperands();
4175 std::swap(A, B);
4176 }
4177 if (A == Op0) { // A&(A^B) -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00004178 Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004179 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004180 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004181 }
4182 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004183
4184 // (A&((~A)|B)) -> A&B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004185 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4186 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004187 return BinaryOperator::CreateAnd(A, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004188 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4189 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004190 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004191 }
4192
Reid Spencere4d87aa2006-12-23 06:05:41 +00004193 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4194 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004195 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004196 return R;
4197
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004198 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4199 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4200 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004201 }
4202
Chris Lattner6fc205f2006-05-05 06:39:07 +00004203 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004204 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4205 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4206 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4207 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004208 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004209 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004210 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4211 I.getType(), TD) &&
4212 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4213 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004214 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004215 Op1C->getOperand(0),
4216 I.getName());
4217 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004218 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004219 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004220 }
Chris Lattnere511b742006-11-14 07:46:50 +00004221
4222 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004223 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4224 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4225 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004226 SI0->getOperand(1) == SI1->getOperand(1) &&
4227 (SI0->hasOneUse() || SI1->hasOneUse())) {
4228 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004229 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004230 SI1->getOperand(0),
4231 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004232 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004233 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004234 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004235 }
4236
Evan Cheng8db90722008-10-14 17:15:11 +00004237 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004238 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4239 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4240 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng8db90722008-10-14 17:15:11 +00004241 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4242 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner99c65742007-10-24 05:38:08 +00004243 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4244 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4245 // If either of the constants are nans, then the whole thing returns
4246 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004247 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersond672ecb2009-07-03 00:17:18 +00004248 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00004249 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
4250 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner99c65742007-10-24 05:38:08 +00004251 }
Evan Cheng8db90722008-10-14 17:15:11 +00004252 } else {
4253 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4254 FCmpInst::Predicate Op0CC, Op1CC;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004255 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4256 m_Value(Op0RHS)), *Context) &&
4257 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4258 m_Value(Op1RHS)), *Context)) {
Evan Cheng4990b252008-10-14 18:13:38 +00004259 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4260 // Swap RHS operands to match LHS.
4261 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4262 std::swap(Op1LHS, Op1RHS);
4263 }
Evan Cheng8db90722008-10-14 17:15:11 +00004264 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4265 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4266 if (Op0CC == Op1CC)
Owen Anderson333c4002009-07-09 23:48:35 +00004267 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4268 Op0LHS, Op0RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00004269 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4270 Op1CC == FCmpInst::FCMP_FALSE)
Owen Andersond672ecb2009-07-03 00:17:18 +00004271 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng8db90722008-10-14 17:15:11 +00004272 else if (Op0CC == FCmpInst::FCMP_TRUE)
4273 return ReplaceInstUsesWith(I, Op1);
4274 else if (Op1CC == FCmpInst::FCMP_TRUE)
4275 return ReplaceInstUsesWith(I, Op0);
4276 bool Op0Ordered;
4277 bool Op1Ordered;
4278 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4279 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4280 if (Op1Pred == 0) {
4281 std::swap(Op0, Op1);
4282 std::swap(Op0Pred, Op1Pred);
4283 std::swap(Op0Ordered, Op1Ordered);
4284 }
4285 if (Op0Pred == 0) {
4286 // uno && ueq -> uno && (uno || eq) -> ueq
4287 // ord && olt -> ord && (ord && lt) -> olt
4288 if (Op0Ordered == Op1Ordered)
4289 return ReplaceInstUsesWith(I, Op1);
4290 // uno && oeq -> uno && (ord && eq) -> false
4291 // uno && ord -> false
4292 if (!Op0Ordered)
Owen Andersond672ecb2009-07-03 00:17:18 +00004293 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng8db90722008-10-14 17:15:11 +00004294 // ord && ueq -> ord && (uno || eq) -> oeq
4295 return cast<Instruction>(getFCmpValue(true, Op1Pred,
Owen Andersond672ecb2009-07-03 00:17:18 +00004296 Op0LHS, Op0RHS, Context));
Evan Cheng8db90722008-10-14 17:15:11 +00004297 }
4298 }
4299 }
4300 }
Chris Lattner99c65742007-10-24 05:38:08 +00004301 }
4302 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004303
Chris Lattner7e708292002-06-25 16:13:24 +00004304 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004305}
4306
Chris Lattner8c34cd22008-10-05 02:13:19 +00004307/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4308/// capable of providing pieces of a bswap. The subexpression provides pieces
4309/// of a bswap if it is proven that each of the non-zero bytes in the output of
4310/// the expression came from the corresponding "byte swapped" byte in some other
4311/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4312/// we know that the expression deposits the low byte of %X into the high byte
4313/// of the bswap result and that all other bytes are zero. This expression is
4314/// accepted, the high byte of ByteValues is set to X to indicate a correct
4315/// match.
4316///
4317/// This function returns true if the match was unsuccessful and false if so.
4318/// On entry to the function the "OverallLeftShift" is a signed integer value
4319/// indicating the number of bytes that the subexpression is later shifted. For
4320/// example, if the expression is later right shifted by 16 bits, the
4321/// OverallLeftShift value would be -2 on entry. This is used to specify which
4322/// byte of ByteValues is actually being set.
4323///
4324/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4325/// byte is masked to zero by a user. For example, in (X & 255), X will be
4326/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4327/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4328/// always in the local (OverallLeftShift) coordinate space.
4329///
4330static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4331 SmallVector<Value*, 8> &ByteValues) {
4332 if (Instruction *I = dyn_cast<Instruction>(V)) {
4333 // If this is an or instruction, it may be an inner node of the bswap.
4334 if (I->getOpcode() == Instruction::Or) {
4335 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4336 ByteValues) ||
4337 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4338 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004339 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004340
4341 // If this is a logical shift by a constant multiple of 8, recurse with
4342 // OverallLeftShift and ByteMask adjusted.
4343 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4344 unsigned ShAmt =
4345 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4346 // Ensure the shift amount is defined and of a byte value.
4347 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4348 return true;
4349
4350 unsigned ByteShift = ShAmt >> 3;
4351 if (I->getOpcode() == Instruction::Shl) {
4352 // X << 2 -> collect(X, +2)
4353 OverallLeftShift += ByteShift;
4354 ByteMask >>= ByteShift;
4355 } else {
4356 // X >>u 2 -> collect(X, -2)
4357 OverallLeftShift -= ByteShift;
4358 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004359 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004360 }
4361
4362 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4363 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4364
4365 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4366 ByteValues);
4367 }
4368
4369 // If this is a logical 'and' with a mask that clears bytes, clear the
4370 // corresponding bytes in ByteMask.
4371 if (I->getOpcode() == Instruction::And &&
4372 isa<ConstantInt>(I->getOperand(1))) {
4373 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4374 unsigned NumBytes = ByteValues.size();
4375 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4376 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4377
4378 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4379 // If this byte is masked out by a later operation, we don't care what
4380 // the and mask is.
4381 if ((ByteMask & (1 << i)) == 0)
4382 continue;
4383
4384 // If the AndMask is all zeros for this byte, clear the bit.
4385 APInt MaskB = AndMask & Byte;
4386 if (MaskB == 0) {
4387 ByteMask &= ~(1U << i);
4388 continue;
4389 }
4390
4391 // If the AndMask is not all ones for this byte, it's not a bytezap.
4392 if (MaskB != Byte)
4393 return true;
4394
4395 // Otherwise, this byte is kept.
4396 }
4397
4398 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4399 ByteValues);
4400 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004401 }
4402
Chris Lattner8c34cd22008-10-05 02:13:19 +00004403 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4404 // the input value to the bswap. Some observations: 1) if more than one byte
4405 // is demanded from this input, then it could not be successfully assembled
4406 // into a byteswap. At least one of the two bytes would not be aligned with
4407 // their ultimate destination.
4408 if (!isPowerOf2_32(ByteMask)) return true;
4409 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004410
Chris Lattner8c34cd22008-10-05 02:13:19 +00004411 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4412 // is demanded, it needs to go into byte 0 of the result. This means that the
4413 // byte needs to be shifted until it lands in the right byte bucket. The
4414 // shift amount depends on the position: if the byte is coming from the high
4415 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4416 // low part, it must be shifted left.
4417 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4418 if (InputByteNo < ByteValues.size()/2) {
4419 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4420 return true;
4421 } else {
4422 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4423 return true;
4424 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004425
4426 // If the destination byte value is already defined, the values are or'd
4427 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004428 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004429 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004430 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004431 return false;
4432}
4433
4434/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4435/// If so, insert the new bswap intrinsic and return it.
4436Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004437 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004438 if (!ITy || ITy->getBitWidth() % 16 ||
4439 // ByteMask only allows up to 32-byte values.
4440 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004441 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004442
4443 /// ByteValues - For each byte of the result, we keep track of which value
4444 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004445 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004446 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004447
4448 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004449 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4450 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004451 return 0;
4452
4453 // Check to see if all of the bytes come from the same value.
4454 Value *V = ByteValues[0];
4455 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4456
4457 // Check to make sure that all of the bytes come from the same value.
4458 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4459 if (ByteValues[i] != V)
4460 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004461 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004462 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004463 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004464 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004465}
4466
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004467/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4468/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4469/// we can simplify this expression to "cond ? C : D or B".
4470static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004471 Value *C, Value *D,
4472 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004473 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004474 Value *Cond = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004475 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004476 return 0;
4477
Chris Lattnera6a474d2008-11-16 04:26:55 +00004478 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004479 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004480 return SelectInst::Create(Cond, C, B);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004481 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004482 return SelectInst::Create(Cond, C, B);
4483 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004484 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004485 return SelectInst::Create(Cond, C, D);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004486 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004487 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004488 return 0;
4489}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004490
Chris Lattner69d4ced2008-11-16 05:20:07 +00004491/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4492Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4493 ICmpInst *LHS, ICmpInst *RHS) {
4494 Value *Val, *Val2;
4495 ConstantInt *LHSCst, *RHSCst;
4496 ICmpInst::Predicate LHSCC, RHSCC;
4497
4498 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004499 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4500 m_ConstantInt(LHSCst)), *Context) ||
4501 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4502 m_ConstantInt(RHSCst)), *Context))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004503 return 0;
4504
4505 // From here on, we only handle:
4506 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4507 if (Val != Val2) return 0;
4508
4509 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4510 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4511 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4512 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4513 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4514 return 0;
4515
4516 // We can't fold (ugt x, C) | (sgt x, C2).
4517 if (!PredicatesFoldable(LHSCC, RHSCC))
4518 return 0;
4519
4520 // Ensure that the larger constant is on the RHS.
4521 bool ShouldSwap;
4522 if (ICmpInst::isSignedPredicate(LHSCC) ||
4523 (ICmpInst::isEquality(LHSCC) &&
4524 ICmpInst::isSignedPredicate(RHSCC)))
4525 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4526 else
4527 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4528
4529 if (ShouldSwap) {
4530 std::swap(LHS, RHS);
4531 std::swap(LHSCst, RHSCst);
4532 std::swap(LHSCC, RHSCC);
4533 }
4534
4535 // At this point, we know we have have two icmp instructions
4536 // comparing a value against two constants and or'ing the result
4537 // together. Because of the above check, we know that we only have
4538 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4539 // FoldICmpLogical check above), that the two constants are not
4540 // equal.
4541 assert(LHSCst != RHSCst && "Compares not folded above?");
4542
4543 switch (LHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00004544 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004545 case ICmpInst::ICMP_EQ:
4546 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00004547 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004548 case ICmpInst::ICMP_EQ:
Owen Andersond672ecb2009-07-03 00:17:18 +00004549 if (LHSCst == SubOne(RHSCst, Context)) {
4550 // (X == 13 | X == 14) -> X-13 <u 2
4551 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004552 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4553 Val->getName()+".off");
4554 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00004555 AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
Owen Anderson333c4002009-07-09 23:48:35 +00004556 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004557 }
4558 break; // (X == 13 | X == 15) -> no change
4559 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4560 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4561 break;
4562 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4563 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4564 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4565 return ReplaceInstUsesWith(I, RHS);
4566 }
4567 break;
4568 case ICmpInst::ICMP_NE:
4569 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00004570 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004571 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4572 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4573 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4574 return ReplaceInstUsesWith(I, LHS);
4575 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4576 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4577 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Andersond672ecb2009-07-03 00:17:18 +00004578 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004579 }
4580 break;
4581 case ICmpInst::ICMP_ULT:
4582 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00004583 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004584 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4585 break;
4586 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4587 // If RHSCst is [us]MAXINT, it is always false. Not handling
4588 // this can cause overflow.
4589 if (RHSCst->isMaxValue(false))
4590 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004591 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4592 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004593 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4594 break;
4595 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4596 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4597 return ReplaceInstUsesWith(I, RHS);
4598 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4599 break;
4600 }
4601 break;
4602 case ICmpInst::ICMP_SLT:
4603 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00004604 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004605 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4606 break;
4607 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4608 // If RHSCst is [us]MAXINT, it is always false. Not handling
4609 // this can cause overflow.
4610 if (RHSCst->isMaxValue(true))
4611 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004612 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4613 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004614 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4615 break;
4616 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4617 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4618 return ReplaceInstUsesWith(I, RHS);
4619 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4620 break;
4621 }
4622 break;
4623 case ICmpInst::ICMP_UGT:
4624 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00004625 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004626 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4627 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4628 return ReplaceInstUsesWith(I, LHS);
4629 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4630 break;
4631 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4632 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Andersond672ecb2009-07-03 00:17:18 +00004633 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004634 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4635 break;
4636 }
4637 break;
4638 case ICmpInst::ICMP_SGT:
4639 switch (RHSCC) {
Torok Edwinc25e7582009-07-11 20:10:48 +00004640 default: LLVM_UNREACHABLE("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004641 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4642 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4643 return ReplaceInstUsesWith(I, LHS);
4644 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4645 break;
4646 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4647 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Andersond672ecb2009-07-03 00:17:18 +00004648 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004649 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4650 break;
4651 }
4652 break;
4653 }
4654 return 0;
4655}
4656
Bill Wendlinga698a472008-12-01 08:23:25 +00004657/// FoldOrWithConstants - This helper function folds:
4658///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004659/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004660///
4661/// into:
4662///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004663/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004664///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004665/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004666Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004667 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004668 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4669 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004670
Bill Wendling286a0542008-12-02 06:24:20 +00004671 Value *V1 = 0;
4672 ConstantInt *CI2 = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004673 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004674
Bill Wendling29976b92008-12-02 06:18:11 +00004675 APInt Xor = CI1->getValue() ^ CI2->getValue();
4676 if (!Xor.isAllOnesValue()) return 0;
4677
Bill Wendling286a0542008-12-02 06:24:20 +00004678 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004679 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004680 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4681 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004682 }
4683
4684 return 0;
4685}
4686
Chris Lattner7e708292002-06-25 16:13:24 +00004687Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004688 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004689 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004690
Chris Lattner42593e62007-03-24 23:56:43 +00004691 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004692 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004693
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004694 // or X, X = X
4695 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004696 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004697
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004698 // See if we can simplify any instructions used by the instruction whose sole
4699 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004700 if (SimplifyDemandedInstructionBits(I))
4701 return &I;
4702 if (isa<VectorType>(I.getType())) {
4703 if (isa<ConstantAggregateZero>(Op1)) {
4704 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4705 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4706 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4707 return ReplaceInstUsesWith(I, I.getOperand(1));
4708 }
Chris Lattner42593e62007-03-24 23:56:43 +00004709 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004710
Chris Lattner3f5b8772002-05-06 16:14:14 +00004711 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004712 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004713 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004714 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004715 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) &&
4716 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004717 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004718 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004719 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004720 return BinaryOperator::CreateAnd(Or,
Owen Andersond672ecb2009-07-03 00:17:18 +00004721 Context->getConstantInt(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004722 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004723
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004724 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004725 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) &&
4726 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004727 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004728 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004729 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004730 return BinaryOperator::CreateXor(Or,
Owen Andersond672ecb2009-07-03 00:17:18 +00004731 Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004732 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004733
4734 // Try to fold constant and into select arguments.
4735 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004736 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004737 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004738 if (isa<PHINode>(Op0))
4739 if (Instruction *NV = FoldOpIntoPhi(I))
4740 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004741 }
4742
Chris Lattner4f637d42006-01-06 17:59:59 +00004743 Value *A = 0, *B = 0;
4744 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004745
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004746 if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004747 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4748 return ReplaceInstUsesWith(I, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004749 if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004750 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4751 return ReplaceInstUsesWith(I, Op0);
4752
Chris Lattner6423d4c2006-07-10 20:25:24 +00004753 // (A | B) | C and A | (B | C) -> bswap if possible.
4754 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004755 if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4756 match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4757 (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4758 match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004759 if (Instruction *BSwap = MatchBSwap(I))
4760 return BSwap;
4761 }
4762
Chris Lattner6e4c6492005-05-09 04:58:36 +00004763 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004764 if (Op0->hasOneUse() &&
4765 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004766 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004767 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004768 InsertNewInstBefore(NOr, I);
4769 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004770 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004771 }
4772
4773 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004774 if (Op1->hasOneUse() &&
4775 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004776 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004777 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004778 InsertNewInstBefore(NOr, I);
4779 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004780 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004781 }
4782
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004783 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004784 Value *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004785 if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4786 match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004787 Value *V1 = 0, *V2 = 0, *V3 = 0;
4788 C1 = dyn_cast<ConstantInt>(C);
4789 C2 = dyn_cast<ConstantInt>(D);
4790 if (C1 && C2) { // (A & C1)|(B & C2)
4791 // If we have: ((V + N) & C1) | (V & C2)
4792 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4793 // replace with V+N.
4794 if (C1->getValue() == ~C2->getValue()) {
4795 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004796 match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004797 // Add commutes, try both ways.
4798 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4799 return ReplaceInstUsesWith(I, A);
4800 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4801 return ReplaceInstUsesWith(I, A);
4802 }
4803 // Or commutes, try both ways.
4804 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004805 match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004806 // Add commutes, try both ways.
4807 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4808 return ReplaceInstUsesWith(I, B);
4809 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4810 return ReplaceInstUsesWith(I, B);
4811 }
4812 }
Chris Lattner044e5332007-04-08 08:01:49 +00004813 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004814 }
4815
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004816 // Check to see if we have any common things being and'ed. If so, find the
4817 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004818 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4819 if (A == B) // (A & C)|(A & D) == A & (C|D)
4820 V1 = A, V2 = C, V3 = D;
4821 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4822 V1 = A, V2 = B, V3 = C;
4823 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4824 V1 = C, V2 = A, V3 = D;
4825 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4826 V1 = C, V2 = A, V3 = B;
4827
4828 if (V1) {
4829 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004830 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4831 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004832 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004833 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004834
Dan Gohman1975d032008-10-30 20:40:10 +00004835 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004836 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004837 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004838 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004839 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004840 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004841 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004842 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004843 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004844
Bill Wendlingb01865c2008-11-30 13:52:49 +00004845 // ((A&~B)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004846 if ((match(C, m_Not(m_Specific(D)), *Context) &&
4847 match(B, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004848 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004849 // ((~B&A)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004850 if ((match(A, m_Not(m_Specific(D)), *Context) &&
4851 match(B, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004852 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004853 // ((A&~B)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004854 if ((match(C, m_Not(m_Specific(B)), *Context) &&
4855 match(D, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004856 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004857 // ((~B&A)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004858 if ((match(A, m_Not(m_Specific(B)), *Context) &&
4859 match(D, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004860 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004861 }
Chris Lattnere511b742006-11-14 07:46:50 +00004862
4863 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004864 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4865 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4866 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004867 SI0->getOperand(1) == SI1->getOperand(1) &&
4868 (SI0->hasOneUse() || SI1->hasOneUse())) {
4869 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004870 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004871 SI1->getOperand(0),
4872 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004873 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004874 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004875 }
4876 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004877
Bill Wendlingb3833d12008-12-01 01:07:11 +00004878 // ((A|B)&1)|(B&-2) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004879 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4880 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004881 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004882 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004883 }
4884 // (B&-2)|((A|B)&1) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004885 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4886 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004887 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004888 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004889 }
4890
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004891 if (match(Op0, m_Not(m_Value(A)), *Context)) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004892 if (A == Op1) // ~A | A == -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004893 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004894 } else {
4895 A = 0;
4896 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004897 // Note, A is still live here!
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004898 if (match(Op1, m_Not(m_Value(B)), *Context)) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004899 if (Op0 == B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004900 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004901
Misha Brukmancb6267b2004-07-30 12:50:08 +00004902 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004903 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004904 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004905 I.getName()+".demorgan"), I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004906 return BinaryOperator::CreateNot(*Context, And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004907 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004908 }
Chris Lattnera2881962003-02-18 19:28:33 +00004909
Reid Spencere4d87aa2006-12-23 06:05:41 +00004910 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4911 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004912 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004913 return R;
4914
Chris Lattner69d4ced2008-11-16 05:20:07 +00004915 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4916 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4917 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004918 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004919
4920 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004921 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004922 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004923 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004924 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4925 !isa<ICmpInst>(Op1C->getOperand(0))) {
4926 const Type *SrcTy = Op0C->getOperand(0)->getType();
4927 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4928 // Only do this if the casts both really cause code to be
4929 // generated.
4930 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4931 I.getType(), TD) &&
4932 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4933 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004934 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004935 Op1C->getOperand(0),
4936 I.getName());
4937 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004938 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004939 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004940 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004941 }
Chris Lattner99c65742007-10-24 05:38:08 +00004942 }
4943
4944
4945 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4946 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4947 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4948 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004949 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004950 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004951 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4952 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4953 // If either of the constants are nans, then the whole thing returns
4954 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004955 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersond672ecb2009-07-03 00:17:18 +00004956 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner99c65742007-10-24 05:38:08 +00004957
4958 // Otherwise, no need to compare the two constants, compare the
4959 // rest.
Owen Anderson333c4002009-07-09 23:48:35 +00004960 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4961 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner99c65742007-10-24 05:38:08 +00004962 }
Evan Cheng40300622008-10-14 18:44:08 +00004963 } else {
4964 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4965 FCmpInst::Predicate Op0CC, Op1CC;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004966 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4967 m_Value(Op0RHS)), *Context) &&
4968 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4969 m_Value(Op1RHS)), *Context)) {
Evan Cheng40300622008-10-14 18:44:08 +00004970 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4971 // Swap RHS operands to match LHS.
4972 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4973 std::swap(Op1LHS, Op1RHS);
4974 }
4975 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4976 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4977 if (Op0CC == Op1CC)
Owen Anderson333c4002009-07-09 23:48:35 +00004978 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4979 Op0LHS, Op0RHS);
Evan Cheng40300622008-10-14 18:44:08 +00004980 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4981 Op1CC == FCmpInst::FCMP_TRUE)
Owen Andersond672ecb2009-07-03 00:17:18 +00004982 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng40300622008-10-14 18:44:08 +00004983 else if (Op0CC == FCmpInst::FCMP_FALSE)
4984 return ReplaceInstUsesWith(I, Op1);
4985 else if (Op1CC == FCmpInst::FCMP_FALSE)
4986 return ReplaceInstUsesWith(I, Op0);
4987 bool Op0Ordered;
4988 bool Op1Ordered;
4989 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4990 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4991 if (Op0Ordered == Op1Ordered) {
4992 // If both are ordered or unordered, return a new fcmp with
4993 // or'ed predicates.
4994 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
Owen Andersond672ecb2009-07-03 00:17:18 +00004995 Op0LHS, Op0RHS, Context);
Evan Cheng40300622008-10-14 18:44:08 +00004996 if (Instruction *I = dyn_cast<Instruction>(RV))
4997 return I;
4998 // Otherwise, it's a constant boolean value...
4999 return ReplaceInstUsesWith(I, RV);
5000 }
5001 }
5002 }
5003 }
Chris Lattner99c65742007-10-24 05:38:08 +00005004 }
5005 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005006
Chris Lattner7e708292002-06-25 16:13:24 +00005007 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005008}
5009
Dan Gohman844731a2008-05-13 00:00:25 +00005010namespace {
5011
Chris Lattnerc317d392004-02-16 01:20:27 +00005012// XorSelf - Implements: X ^ X --> 0
5013struct XorSelf {
5014 Value *RHS;
5015 XorSelf(Value *rhs) : RHS(rhs) {}
5016 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5017 Instruction *apply(BinaryOperator &Xor) const {
5018 return &Xor;
5019 }
5020};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005021
Dan Gohman844731a2008-05-13 00:00:25 +00005022}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005023
Chris Lattner7e708292002-06-25 16:13:24 +00005024Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005025 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005026 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005027
Evan Chengd34af782008-03-25 20:07:13 +00005028 if (isa<UndefValue>(Op1)) {
5029 if (isa<UndefValue>(Op0))
5030 // Handle undef ^ undef -> 0 special case. This is a common
5031 // idiom (misuse).
Owen Andersond672ecb2009-07-03 00:17:18 +00005032 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005033 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005034 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005035
Chris Lattnerc317d392004-02-16 01:20:27 +00005036 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Owen Andersond672ecb2009-07-03 00:17:18 +00005037 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005038 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersond672ecb2009-07-03 00:17:18 +00005039 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005040 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005041
5042 // See if we can simplify any instructions used by the instruction whose sole
5043 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005044 if (SimplifyDemandedInstructionBits(I))
5045 return &I;
5046 if (isa<VectorType>(I.getType()))
5047 if (isa<ConstantAggregateZero>(Op1))
5048 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005049
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005050 // Is this a ~ operation?
Owen Andersond672ecb2009-07-03 00:17:18 +00005051 if (Value *NotOp = dyn_castNotVal(&I, Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005052 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5053 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5054 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5055 if (Op0I->getOpcode() == Instruction::And ||
5056 Op0I->getOpcode() == Instruction::Or) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005057 if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5058 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005059 Instruction *NotY =
Owen Anderson73c6b712009-07-13 20:58:05 +00005060 BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005061 Op0I->getOperand(1)->getName()+".not");
5062 InsertNewInstBefore(NotY, I);
5063 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005064 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005065 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005066 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005067 }
5068 }
5069 }
5070 }
5071
5072
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005073 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005074 if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005075 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005076 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005077 return new ICmpInst(*Context, ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005078 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005079
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005080 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005081 return new FCmpInst(*Context, FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005082 FCI->getOperand(0), FCI->getOperand(1));
5083 }
5084
Nick Lewycky517e1f52008-05-31 19:01:33 +00005085 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5086 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5087 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5088 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5089 Instruction::CastOps Opcode = Op0C->getOpcode();
5090 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005091 if (RHS == Context->getConstantExprCast(Opcode,
5092 Context->getConstantIntTrue(),
Nick Lewycky517e1f52008-05-31 19:01:33 +00005093 Op0C->getDestTy())) {
5094 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
Owen Anderson333c4002009-07-09 23:48:35 +00005095 *Context,
Nick Lewycky517e1f52008-05-31 19:01:33 +00005096 CI->getOpcode(), CI->getInversePredicate(),
5097 CI->getOperand(0), CI->getOperand(1)), I);
5098 NewCI->takeName(CI);
5099 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5100 }
5101 }
5102 }
5103 }
5104 }
5105
Reid Spencere4d87aa2006-12-23 06:05:41 +00005106 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005107 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005108 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5109 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005110 Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5111 Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5112 Context->getConstantInt(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005113 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005114 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005115
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005116 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005117 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005118 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005119 if (RHS->isAllOnesValue()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005120 Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005121 return BinaryOperator::CreateSub(
Owen Andersond672ecb2009-07-03 00:17:18 +00005122 Context->getConstantExprSub(NegOp0CI,
5123 Context->getConstantInt(I.getType(), 1)),
5124 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005125 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005126 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersond672ecb2009-07-03 00:17:18 +00005127 Constant *C =
5128 Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005129 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005130
Chris Lattner7c4049c2004-01-12 19:35:11 +00005131 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005132 } else if (Op0I->getOpcode() == Instruction::Or) {
5133 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005134 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005135 Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005136 // Anything in both C1 and C2 is known to be zero, remove it from
5137 // NewRHS.
Owen Andersond672ecb2009-07-03 00:17:18 +00005138 Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5139 NewRHS = Context->getConstantExprAnd(NewRHS,
5140 Context->getConstantExprNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005141 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005142 I.setOperand(0, Op0I->getOperand(0));
5143 I.setOperand(1, NewRHS);
5144 return &I;
5145 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005146 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005147 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005148 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005149
5150 // Try to fold constant and into select arguments.
5151 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005152 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005153 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005154 if (isa<PHINode>(Op0))
5155 if (Instruction *NV = FoldOpIntoPhi(I))
5156 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005157 }
5158
Owen Andersond672ecb2009-07-03 00:17:18 +00005159 if (Value *X = dyn_castNotVal(Op0, Context)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005160 if (X == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005161 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005162
Owen Andersond672ecb2009-07-03 00:17:18 +00005163 if (Value *X = dyn_castNotVal(Op1, Context)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005164 if (X == Op0)
Owen Andersond672ecb2009-07-03 00:17:18 +00005165 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005166
Chris Lattner318bf792007-03-18 22:51:34 +00005167
5168 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5169 if (Op1I) {
5170 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005171 if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005172 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005173 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005174 I.swapOperands();
5175 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005176 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005177 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005178 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005179 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005180 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005181 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005182 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005183 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005184 } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) &&
5185 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005186 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005187 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005188 std::swap(A, B);
5189 }
Chris Lattner318bf792007-03-18 22:51:34 +00005190 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005191 I.swapOperands(); // Simplified below.
5192 std::swap(Op0, Op1);
5193 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005194 }
Chris Lattner318bf792007-03-18 22:51:34 +00005195 }
5196
5197 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5198 if (Op0I) {
5199 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005200 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5201 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005202 if (A == Op1) // (B|A)^B == (A|B)^B
5203 std::swap(A, B);
5204 if (B == Op1) { // (A|B)^B == A & ~B
5205 Instruction *NotB =
Owen Anderson73c6b712009-07-13 20:58:05 +00005206 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
5207 Op1, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005208 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005209 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005210 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005211 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005212 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005213 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005214 } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5215 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005216 if (A == Op1) // (A&B)^A -> (B&A)^A
5217 std::swap(A, B);
5218 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005219 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005220 Instruction *N =
Owen Anderson73c6b712009-07-13 20:58:05 +00005221 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005222 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005223 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005224 }
Chris Lattner318bf792007-03-18 22:51:34 +00005225 }
5226
5227 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5228 if (Op0I && Op1I && Op0I->isShift() &&
5229 Op0I->getOpcode() == Op1I->getOpcode() &&
5230 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5231 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5232 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005233 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005234 Op1I->getOperand(0),
5235 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005236 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005237 Op1I->getOperand(1));
5238 }
5239
5240 if (Op0I && Op1I) {
5241 Value *A, *B, *C, *D;
5242 // (A & B)^(A | B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005243 if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5244 match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005245 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005246 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005247 }
5248 // (A | B)^(A & B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005249 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5250 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005251 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005252 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005253 }
5254
5255 // (A & B)^(C & D)
5256 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005257 match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5258 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005259 // (X & Y)^(X & Y) -> (Y^Z) & X
5260 Value *X = 0, *Y = 0, *Z = 0;
5261 if (A == C)
5262 X = A, Y = B, Z = D;
5263 else if (A == D)
5264 X = A, Y = B, Z = C;
5265 else if (B == C)
5266 X = B, Y = A, Z = D;
5267 else if (B == D)
5268 X = B, Y = A, Z = C;
5269
5270 if (X) {
5271 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005272 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5273 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005274 }
5275 }
5276 }
5277
Reid Spencere4d87aa2006-12-23 06:05:41 +00005278 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5279 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005280 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005281 return R;
5282
Chris Lattner6fc205f2006-05-05 06:39:07 +00005283 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005284 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005285 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005286 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5287 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005288 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005289 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005290 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5291 I.getType(), TD) &&
5292 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5293 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005294 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005295 Op1C->getOperand(0),
5296 I.getName());
5297 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005298 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005299 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005300 }
Chris Lattner99c65742007-10-24 05:38:08 +00005301 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005302
Chris Lattner7e708292002-06-25 16:13:24 +00005303 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005304}
5305
Owen Andersond672ecb2009-07-03 00:17:18 +00005306static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005307 LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005308 return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005309}
Chris Lattnera96879a2004-09-29 17:40:11 +00005310
Dan Gohman6de29f82009-06-15 22:12:54 +00005311static bool HasAddOverflow(ConstantInt *Result,
5312 ConstantInt *In1, ConstantInt *In2,
5313 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005314 if (IsSigned)
5315 if (In2->getValue().isNegative())
5316 return Result->getValue().sgt(In1->getValue());
5317 else
5318 return Result->getValue().slt(In1->getValue());
5319 else
5320 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005321}
5322
Dan Gohman6de29f82009-06-15 22:12:54 +00005323/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005324/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005325static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005326 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005327 bool IsSigned = false) {
5328 Result = Context->getConstantExprAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005329
Dan Gohman6de29f82009-06-15 22:12:54 +00005330 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5331 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005332 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5333 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5334 ExtractElement(In1, Idx, Context),
5335 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005336 IsSigned))
5337 return true;
5338 }
5339 return false;
5340 }
5341
5342 return HasAddOverflow(cast<ConstantInt>(Result),
5343 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5344 IsSigned);
5345}
5346
5347static bool HasSubOverflow(ConstantInt *Result,
5348 ConstantInt *In1, ConstantInt *In2,
5349 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005350 if (IsSigned)
5351 if (In2->getValue().isNegative())
5352 return Result->getValue().slt(In1->getValue());
5353 else
5354 return Result->getValue().sgt(In1->getValue());
5355 else
5356 return Result->getValue().ugt(In1->getValue());
5357}
5358
Dan Gohman6de29f82009-06-15 22:12:54 +00005359/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5360/// overflowed for this type.
5361static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005362 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005363 bool IsSigned = false) {
5364 Result = Context->getConstantExprSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005365
5366 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5367 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005368 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5369 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5370 ExtractElement(In1, Idx, Context),
5371 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005372 IsSigned))
5373 return true;
5374 }
5375 return false;
5376 }
5377
5378 return HasSubOverflow(cast<ConstantInt>(Result),
5379 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5380 IsSigned);
5381}
5382
Chris Lattner574da9b2005-01-13 20:14:25 +00005383/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5384/// code necessary to compute the offset from the base pointer (without adding
5385/// in the base pointer). Return the result as a signed integer of intptr size.
5386static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5387 TargetData &TD = IC.getTargetData();
5388 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005389 const Type *IntPtrTy = TD.getIntPtrType();
Owen Anderson07cf79e2009-07-06 23:00:19 +00005390 LLVMContext *Context = IC.getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00005391 Value *Result = Context->getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005392
5393 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005394 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005395 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005396
Gabor Greif177dd3f2008-06-12 21:37:33 +00005397 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5398 ++i, ++GTI) {
5399 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005400 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005401 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5402 if (OpC->isZero()) continue;
5403
5404 // Handle a struct index, which adds its field offset to the pointer.
5405 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5406 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5407
5408 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005409 Result =
5410 Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005411 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005412 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005413 BinaryOperator::CreateAdd(Result,
Owen Andersond672ecb2009-07-03 00:17:18 +00005414 Context->getConstantInt(IntPtrTy, Size),
Chris Lattnere62f0212007-04-28 04:52:43 +00005415 GEP->getName()+".offs"), I);
5416 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005417 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005418
Owen Andersond672ecb2009-07-03 00:17:18 +00005419 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5420 Constant *OC =
5421 Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5422 Scale = Context->getConstantExprMul(OC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005423 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005424 Result = Context->getConstantExprAdd(RC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005425 else {
5426 // Emit an add instruction.
5427 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005428 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005429 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005430 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005431 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005432 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005433 // Convert to correct type.
5434 if (Op->getType() != IntPtrTy) {
5435 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005436 Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005437 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005438 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5439 true,
5440 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005441 }
5442 if (Size != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005443 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
Chris Lattnere62f0212007-04-28 04:52:43 +00005444 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005445 Op = Context->getConstantExprMul(OpC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005446 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005447 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005448 GEP->getName()+".idx"), I);
5449 }
5450
5451 // Emit an add instruction.
5452 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005453 Result = Context->getConstantExprAdd(cast<Constant>(Op),
Chris Lattnere62f0212007-04-28 04:52:43 +00005454 cast<Constant>(Result));
5455 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005456 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005457 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005458 }
5459 return Result;
5460}
5461
Chris Lattner10c0d912008-04-22 02:53:33 +00005462
5463/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5464/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5465/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5466/// complex, and scales are involved. The above expression would also be legal
5467/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5468/// later form is less amenable to optimization though, and we are allowed to
5469/// generate the first by knowing that pointer arithmetic doesn't overflow.
5470///
5471/// If we can't emit an optimized form for this expression, this returns null.
5472///
5473static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5474 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005475 TargetData &TD = IC.getTargetData();
5476 gep_type_iterator GTI = gep_type_begin(GEP);
5477
5478 // Check to see if this gep only has a single variable index. If so, and if
5479 // any constant indices are a multiple of its scale, then we can compute this
5480 // in terms of the scale of the variable index. For example, if the GEP
5481 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5482 // because the expression will cross zero at the same point.
5483 unsigned i, e = GEP->getNumOperands();
5484 int64_t Offset = 0;
5485 for (i = 1; i != e; ++i, ++GTI) {
5486 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5487 // Compute the aggregate offset of constant indices.
5488 if (CI->isZero()) continue;
5489
5490 // Handle a struct index, which adds its field offset to the pointer.
5491 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5492 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5493 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005494 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005495 Offset += Size*CI->getSExtValue();
5496 }
5497 } else {
5498 // Found our variable index.
5499 break;
5500 }
5501 }
5502
5503 // If there are no variable indices, we must have a constant offset, just
5504 // evaluate it the general way.
5505 if (i == e) return 0;
5506
5507 Value *VariableIdx = GEP->getOperand(i);
5508 // Determine the scale factor of the variable element. For example, this is
5509 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005510 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005511
5512 // Verify that there are no other variable indices. If so, emit the hard way.
5513 for (++i, ++GTI; i != e; ++i, ++GTI) {
5514 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5515 if (!CI) return 0;
5516
5517 // Compute the aggregate offset of constant indices.
5518 if (CI->isZero()) continue;
5519
5520 // Handle a struct index, which adds its field offset to the pointer.
5521 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5522 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5523 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005524 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005525 Offset += Size*CI->getSExtValue();
5526 }
5527 }
5528
5529 // Okay, we know we have a single variable index, which must be a
5530 // pointer/array/vector index. If there is no offset, life is simple, return
5531 // the index.
5532 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5533 if (Offset == 0) {
5534 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5535 // we don't need to bother extending: the extension won't affect where the
5536 // computation crosses zero.
5537 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5538 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5539 VariableIdx->getNameStart(), &I);
5540 return VariableIdx;
5541 }
5542
5543 // Otherwise, there is an index. The computation we will do will be modulo
5544 // the pointer size, so get it.
5545 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5546
5547 Offset &= PtrSizeMask;
5548 VariableScale &= PtrSizeMask;
5549
5550 // To do this transformation, any constant index must be a multiple of the
5551 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5552 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5553 // multiple of the variable scale.
5554 int64_t NewOffs = Offset / (int64_t)VariableScale;
5555 if (Offset != NewOffs*(int64_t)VariableScale)
5556 return 0;
5557
5558 // Okay, we can do this evaluation. Start by converting the index to intptr.
5559 const Type *IntPtrTy = TD.getIntPtrType();
5560 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005561 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005562 true /*SExt*/,
5563 VariableIdx->getNameStart(), &I);
Owen Andersond672ecb2009-07-03 00:17:18 +00005564 Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005565 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005566}
5567
5568
Reid Spencere4d87aa2006-12-23 06:05:41 +00005569/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005570/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005571Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5572 ICmpInst::Predicate Cond,
5573 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005574 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005575
Chris Lattner10c0d912008-04-22 02:53:33 +00005576 // Look through bitcasts.
5577 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5578 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005579
Chris Lattner574da9b2005-01-13 20:14:25 +00005580 Value *PtrBase = GEPLHS->getOperand(0);
5581 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005582 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005583 // This transformation (ignoring the base and scales) is valid because we
5584 // know pointers can't overflow. See if we can output an optimized form.
5585 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5586
5587 // If not, synthesize the offset the hard way.
5588 if (Offset == 0)
5589 Offset = EmitGEPOffset(GEPLHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005590 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersond672ecb2009-07-03 00:17:18 +00005591 Context->getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005592 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005593 // If the base pointers are different, but the indices are the same, just
5594 // compare the base pointer.
5595 if (PtrBase != GEPRHS->getOperand(0)) {
5596 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005597 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005598 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005599 if (IndicesTheSame)
5600 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5601 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5602 IndicesTheSame = false;
5603 break;
5604 }
5605
5606 // If all indices are the same, just compare the base pointers.
5607 if (IndicesTheSame)
Owen Anderson333c4002009-07-09 23:48:35 +00005608 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005609 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005610
5611 // Otherwise, the base pointers are different and the indices are
5612 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005613 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005614 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005615
Chris Lattnere9d782b2005-01-13 22:25:21 +00005616 // If one of the GEPs has all zero indices, recurse.
5617 bool AllZeros = true;
5618 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5619 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5620 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5621 AllZeros = false;
5622 break;
5623 }
5624 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005625 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5626 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005627
5628 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005629 AllZeros = true;
5630 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5631 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5632 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5633 AllZeros = false;
5634 break;
5635 }
5636 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005637 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005638
Chris Lattner4401c9c2005-01-14 00:20:05 +00005639 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5640 // If the GEPs only differ by one index, compare it.
5641 unsigned NumDifferences = 0; // Keep track of # differences.
5642 unsigned DiffOperand = 0; // The operand that differs.
5643 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5644 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005645 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5646 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005647 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005648 NumDifferences = 2;
5649 break;
5650 } else {
5651 if (NumDifferences++) break;
5652 DiffOperand = i;
5653 }
5654 }
5655
5656 if (NumDifferences == 0) // SAME GEP?
5657 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Andersond672ecb2009-07-03 00:17:18 +00005658 Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005659 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005660
Chris Lattner4401c9c2005-01-14 00:20:05 +00005661 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005662 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5663 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005664 // Make sure we do a signed comparison here.
Owen Anderson333c4002009-07-09 23:48:35 +00005665 return new ICmpInst(*Context,
5666 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005667 }
5668 }
5669
Reid Spencere4d87aa2006-12-23 06:05:41 +00005670 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005671 // the result to fold to a constant!
5672 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5673 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5674 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5675 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5676 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005677 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005678 }
5679 }
5680 return 0;
5681}
5682
Chris Lattnera5406232008-05-19 20:18:56 +00005683/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5684///
5685Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5686 Instruction *LHSI,
5687 Constant *RHSC) {
5688 if (!isa<ConstantFP>(RHSC)) return 0;
5689 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5690
5691 // Get the width of the mantissa. We don't want to hack on conversions that
5692 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005693 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005694 if (MantissaWidth == -1) return 0; // Unknown.
5695
5696 // Check to see that the input is converted from an integer type that is small
5697 // enough that preserves all bits. TODO: check here for "known" sign bits.
5698 // 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 +00005699 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005700
5701 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005702 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5703 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005704 ++InputSize;
5705
5706 // If the conversion would lose info, don't hack on this.
5707 if ((int)InputSize > MantissaWidth)
5708 return 0;
5709
5710 // Otherwise, we can potentially simplify the comparison. We know that it
5711 // will always come through as an integer value and we know the constant is
5712 // not a NAN (it would have been previously simplified).
5713 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5714
5715 ICmpInst::Predicate Pred;
5716 switch (I.getPredicate()) {
Torok Edwinc25e7582009-07-11 20:10:48 +00005717 default: LLVM_UNREACHABLE("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005718 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005719 case FCmpInst::FCMP_OEQ:
5720 Pred = ICmpInst::ICMP_EQ;
5721 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005722 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005723 case FCmpInst::FCMP_OGT:
5724 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5725 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005726 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005727 case FCmpInst::FCMP_OGE:
5728 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5729 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005730 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005731 case FCmpInst::FCMP_OLT:
5732 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5733 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005734 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005735 case FCmpInst::FCMP_OLE:
5736 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5737 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005738 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005739 case FCmpInst::FCMP_ONE:
5740 Pred = ICmpInst::ICMP_NE;
5741 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005742 case FCmpInst::FCMP_ORD:
Owen Andersond672ecb2009-07-03 00:17:18 +00005743 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005744 case FCmpInst::FCMP_UNO:
Owen Andersond672ecb2009-07-03 00:17:18 +00005745 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005746 }
5747
5748 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5749
5750 // Now we know that the APFloat is a normal number, zero or inf.
5751
Chris Lattner85162782008-05-20 03:50:52 +00005752 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005753 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005754 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005755
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005756 if (!LHSUnsigned) {
5757 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5758 // and large values.
5759 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5760 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5761 APFloat::rmNearestTiesToEven);
5762 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5763 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5764 Pred == ICmpInst::ICMP_SLE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005765 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5766 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005767 }
5768 } else {
5769 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5770 // +INF and large values.
5771 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5772 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5773 APFloat::rmNearestTiesToEven);
5774 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5775 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5776 Pred == ICmpInst::ICMP_ULE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005777 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5778 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005779 }
Chris Lattnera5406232008-05-19 20:18:56 +00005780 }
5781
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005782 if (!LHSUnsigned) {
5783 // See if the RHS value is < SignedMin.
5784 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5785 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5786 APFloat::rmNearestTiesToEven);
5787 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5788 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5789 Pred == ICmpInst::ICMP_SGE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005790 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5791 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005792 }
Chris Lattnera5406232008-05-19 20:18:56 +00005793 }
5794
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005795 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5796 // [0, UMAX], but it may still be fractional. See if it is fractional by
5797 // casting the FP value to the integer value and back, checking for equality.
5798 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005799 Constant *RHSInt = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005800 ? Context->getConstantExprFPToUI(RHSC, IntTy)
5801 : Context->getConstantExprFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005802 if (!RHS.isZero()) {
5803 bool Equal = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005804 ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5805 : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005806 if (!Equal) {
5807 // If we had a comparison against a fractional value, we have to adjust
5808 // the compare predicate and sometimes the value. RHSC is rounded towards
5809 // zero at this point.
5810 switch (Pred) {
Torok Edwinc25e7582009-07-11 20:10:48 +00005811 default: LLVM_UNREACHABLE("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005812 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Andersond672ecb2009-07-03 00:17:18 +00005813 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005814 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Andersond672ecb2009-07-03 00:17:18 +00005815 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005816 case ICmpInst::ICMP_ULE:
5817 // (float)int <= 4.4 --> int <= 4
5818 // (float)int <= -4.4 --> false
5819 if (RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005820 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005821 break;
5822 case ICmpInst::ICMP_SLE:
5823 // (float)int <= 4.4 --> int <= 4
5824 // (float)int <= -4.4 --> int < -4
5825 if (RHS.isNegative())
5826 Pred = ICmpInst::ICMP_SLT;
5827 break;
5828 case ICmpInst::ICMP_ULT:
5829 // (float)int < -4.4 --> false
5830 // (float)int < 4.4 --> int <= 4
5831 if (RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005832 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005833 Pred = ICmpInst::ICMP_ULE;
5834 break;
5835 case ICmpInst::ICMP_SLT:
5836 // (float)int < -4.4 --> int < -4
5837 // (float)int < 4.4 --> int <= 4
5838 if (!RHS.isNegative())
5839 Pred = ICmpInst::ICMP_SLE;
5840 break;
5841 case ICmpInst::ICMP_UGT:
5842 // (float)int > 4.4 --> int > 4
5843 // (float)int > -4.4 --> true
5844 if (RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005845 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005846 break;
5847 case ICmpInst::ICMP_SGT:
5848 // (float)int > 4.4 --> int > 4
5849 // (float)int > -4.4 --> int >= -4
5850 if (RHS.isNegative())
5851 Pred = ICmpInst::ICMP_SGE;
5852 break;
5853 case ICmpInst::ICMP_UGE:
5854 // (float)int >= -4.4 --> true
5855 // (float)int >= 4.4 --> int > 4
5856 if (!RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005857 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005858 Pred = ICmpInst::ICMP_UGT;
5859 break;
5860 case ICmpInst::ICMP_SGE:
5861 // (float)int >= -4.4 --> int >= -4
5862 // (float)int >= 4.4 --> int > 4
5863 if (!RHS.isNegative())
5864 Pred = ICmpInst::ICMP_SGT;
5865 break;
5866 }
Chris Lattnera5406232008-05-19 20:18:56 +00005867 }
5868 }
5869
5870 // Lower this FP comparison into an appropriate integer version of the
5871 // comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00005872 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005873}
5874
Reid Spencere4d87aa2006-12-23 06:05:41 +00005875Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5876 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005877 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005878
Chris Lattner58e97462007-01-14 19:42:17 +00005879 // Fold trivial predicates.
5880 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005881 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005882 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005883 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005884
5885 // Simplify 'fcmp pred X, X'
5886 if (Op0 == Op1) {
5887 switch (I.getPredicate()) {
Torok Edwinc25e7582009-07-11 20:10:48 +00005888 default: LLVM_UNREACHABLE("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005889 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5890 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5891 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Andersond672ecb2009-07-03 00:17:18 +00005892 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005893 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5894 case FCmpInst::FCMP_OLT: // True if ordered and less than
5895 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Andersond672ecb2009-07-03 00:17:18 +00005896 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005897
5898 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5899 case FCmpInst::FCMP_ULT: // True if unordered or less than
5900 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5901 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5902 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5903 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersond672ecb2009-07-03 00:17:18 +00005904 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005905 return &I;
5906
5907 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5908 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5909 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5910 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5911 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5912 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersond672ecb2009-07-03 00:17:18 +00005913 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005914 return &I;
5915 }
5916 }
5917
Reid Spencere4d87aa2006-12-23 06:05:41 +00005918 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005919 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005920
Reid Spencere4d87aa2006-12-23 06:05:41 +00005921 // Handle fcmp with constant RHS
5922 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005923 // If the constant is a nan, see if we can fold the comparison based on it.
5924 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5925 if (CFP->getValueAPF().isNaN()) {
5926 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Andersond672ecb2009-07-03 00:17:18 +00005927 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005928 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5929 "Comparison must be either ordered or unordered!");
5930 // True if unordered.
Owen Andersond672ecb2009-07-03 00:17:18 +00005931 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005932 }
5933 }
5934
Reid Spencere4d87aa2006-12-23 06:05:41 +00005935 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5936 switch (LHSI->getOpcode()) {
5937 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005938 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5939 // block. If in the same block, we're encouraging jump threading. If
5940 // not, we are just pessimizing the code by making an i1 phi.
5941 if (LHSI->getParent() == I.getParent())
5942 if (Instruction *NV = FoldOpIntoPhi(I))
5943 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005944 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005945 case Instruction::SIToFP:
5946 case Instruction::UIToFP:
5947 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5948 return NV;
5949 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005950 case Instruction::Select:
5951 // If either operand of the select is a constant, we can fold the
5952 // comparison into the select arms, which will cause one to be
5953 // constant folded and the select turned into a bitwise or.
5954 Value *Op1 = 0, *Op2 = 0;
5955 if (LHSI->hasOneUse()) {
5956 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5957 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005958 Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005959 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005960 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005961 LHSI->getOperand(2), RHSC,
5962 I.getName()), I);
5963 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5964 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005965 Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005966 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005967 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005968 LHSI->getOperand(1), RHSC,
5969 I.getName()), I);
5970 }
5971 }
5972
5973 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005974 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005975 break;
5976 }
5977 }
5978
5979 return Changed ? &I : 0;
5980}
5981
5982Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5983 bool Changed = SimplifyCompare(I);
5984 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5985 const Type *Ty = Op0->getType();
5986
5987 // icmp X, X
5988 if (Op0 == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005989 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005990 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005991
5992 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005993 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005994
Reid Spencere4d87aa2006-12-23 06:05:41 +00005995 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005996 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005997 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5998 isa<ConstantPointerNull>(Op0)) &&
5999 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00006000 isa<ConstantPointerNull>(Op1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00006001 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006002 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00006003
Reid Spencere4d87aa2006-12-23 06:05:41 +00006004 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00006005 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006006 switch (I.getPredicate()) {
Torok Edwinc25e7582009-07-11 20:10:48 +00006007 default: LLVM_UNREACHABLE("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006008 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006009 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00006010 InsertNewInstBefore(Xor, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00006011 return BinaryOperator::CreateNot(*Context, Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006012 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006013 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006014 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006015
Reid Spencere4d87aa2006-12-23 06:05:41 +00006016 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006017 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006018 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006019 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Owen Anderson73c6b712009-07-13 20:58:05 +00006020 Instruction *Not = BinaryOperator::CreateNot(*Context,
6021 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006022 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006023 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006024 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006025 case ICmpInst::ICMP_SGT:
6026 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006027 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006028 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00006029 Instruction *Not = BinaryOperator::CreateNot(*Context,
6030 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006031 InsertNewInstBefore(Not, I);
6032 return BinaryOperator::CreateAnd(Not, Op0);
6033 }
6034 case ICmpInst::ICMP_UGE:
6035 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6036 // FALL THROUGH
6037 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Owen Anderson73c6b712009-07-13 20:58:05 +00006038 Instruction *Not = BinaryOperator::CreateNot(*Context,
6039 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006040 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006041 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006042 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006043 case ICmpInst::ICMP_SGE:
6044 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6045 // FALL THROUGH
6046 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00006047 Instruction *Not = BinaryOperator::CreateNot(*Context,
6048 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006049 InsertNewInstBefore(Not, I);
6050 return BinaryOperator::CreateOr(Not, Op0);
6051 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006052 }
Chris Lattner8b170942002-08-09 23:47:40 +00006053 }
6054
Dan Gohman1c8491e2009-04-25 17:12:48 +00006055 unsigned BitWidth = 0;
6056 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006057 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6058 else if (Ty->isIntOrIntVector())
6059 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006060
6061 bool isSignBit = false;
6062
Dan Gohman81b28ce2008-09-16 18:46:06 +00006063 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006064 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006065 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006066
Chris Lattnerb6566012008-01-05 01:18:20 +00006067 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6068 if (I.isEquality() && CI->isNullValue() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006069 match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006070 // (icmp cond A B) if cond is equality
Owen Anderson333c4002009-07-09 23:48:35 +00006071 return new ICmpInst(*Context, I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006072 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006073
Dan Gohman81b28ce2008-09-16 18:46:06 +00006074 // If we have an icmp le or icmp ge instruction, turn it into the
6075 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6076 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006077 switch (I.getPredicate()) {
6078 default: break;
6079 case ICmpInst::ICMP_ULE:
6080 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006081 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006082 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6083 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006084 case ICmpInst::ICMP_SLE:
6085 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006086 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006087 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6088 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006089 case ICmpInst::ICMP_UGE:
6090 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006091 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006092 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6093 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006094 case ICmpInst::ICMP_SGE:
6095 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006096 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006097 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6098 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006099 }
6100
Chris Lattner183661e2008-07-11 05:40:05 +00006101 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006102 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006103 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006104 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6105 }
6106
6107 // See if we can fold the comparison based on range information we can get
6108 // by checking whether bits are known to be zero or one in the input.
6109 if (BitWidth != 0) {
6110 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6111 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6112
6113 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006114 isSignBit ? APInt::getSignBit(BitWidth)
6115 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006116 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006117 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006118 if (SimplifyDemandedBits(I.getOperandUse(1),
6119 APInt::getAllOnesValue(BitWidth),
6120 Op1KnownZero, Op1KnownOne, 0))
6121 return &I;
6122
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006123 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006124 // in. Compute the Min, Max and RHS values based on the known bits. For the
6125 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006126 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6127 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6128 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6129 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6130 Op0Min, Op0Max);
6131 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6132 Op1Min, Op1Max);
6133 } else {
6134 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6135 Op0Min, Op0Max);
6136 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6137 Op1Min, Op1Max);
6138 }
6139
Chris Lattner183661e2008-07-11 05:40:05 +00006140 // If Min and Max are known to be the same, then SimplifyDemandedBits
6141 // figured out that the LHS is a constant. Just constant fold this now so
6142 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006143 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006144 return new ICmpInst(*Context, I.getPredicate(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006145 Context->getConstantInt(Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006146 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006147 return new ICmpInst(*Context, I.getPredicate(), Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006148 Context->getConstantInt(Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006149
Chris Lattner183661e2008-07-11 05:40:05 +00006150 // Based on the range information we know about the LHS, see if we can
6151 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006152 switch (I.getPredicate()) {
Torok Edwinc25e7582009-07-11 20:10:48 +00006153 default: LLVM_UNREACHABLE("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006154 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006155 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersond672ecb2009-07-03 00:17:18 +00006156 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006157 break;
6158 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006159 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersond672ecb2009-07-03 00:17:18 +00006160 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner84dff672008-07-11 05:08:55 +00006161 break;
6162 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006163 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006164 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006165 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006166 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006167 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006168 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006169 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6170 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006171 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6172 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006173
6174 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6175 if (CI->isMinValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006176 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Owen Anderson73c6b712009-07-13 20:58:05 +00006177 Context->getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006178 }
Chris Lattner84dff672008-07-11 05:08:55 +00006179 break;
6180 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006181 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006182 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006183 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006184 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006185
6186 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006187 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006188 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6189 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006190 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6191 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006192
6193 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6194 if (CI->isMaxValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006195 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006196 Context->getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006197 }
Chris Lattner84dff672008-07-11 05:08:55 +00006198 break;
6199 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006200 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Andersond672ecb2009-07-03 00:17:18 +00006201 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006202 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Andersond672ecb2009-07-03 00:17:18 +00006203 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006204 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006205 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006206 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6207 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006208 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6209 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006210 }
Chris Lattner84dff672008-07-11 05:08:55 +00006211 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006212 case ICmpInst::ICMP_SGT:
6213 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006214 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006215 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006216 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006217
6218 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006219 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006220 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6221 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006222 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6223 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006224 }
6225 break;
6226 case ICmpInst::ICMP_SGE:
6227 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6228 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006229 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006230 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006231 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006232 break;
6233 case ICmpInst::ICMP_SLE:
6234 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6235 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006236 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006237 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006238 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006239 break;
6240 case ICmpInst::ICMP_UGE:
6241 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6242 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006243 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006244 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006245 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006246 break;
6247 case ICmpInst::ICMP_ULE:
6248 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6249 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006250 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006251 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006252 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006253 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006254 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006255
6256 // Turn a signed comparison into an unsigned one if both operands
6257 // are known to have the same sign.
6258 if (I.isSignedPredicate() &&
6259 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6260 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Owen Anderson333c4002009-07-09 23:48:35 +00006261 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006262 }
6263
6264 // Test if the ICmpInst instruction is used exclusively by a select as
6265 // part of a minimum or maximum operation. If so, refrain from doing
6266 // any other folding. This helps out other analyses which understand
6267 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6268 // and CodeGen. And in this case, at least one of the comparison
6269 // operands has at least one user besides the compare (the select),
6270 // which would often largely negate the benefit of folding anyway.
6271 if (I.hasOneUse())
6272 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6273 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6274 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6275 return 0;
6276
6277 // See if we are doing a comparison between a constant and an instruction that
6278 // can be folded into the comparison.
6279 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006280 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006281 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006282 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006283 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006284 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6285 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006286 }
6287
Chris Lattner01deb9d2007-04-03 17:43:25 +00006288 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006289 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6290 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6291 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006292 case Instruction::GetElementPtr:
6293 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006294 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006295 bool isAllZeros = true;
6296 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6297 if (!isa<Constant>(LHSI->getOperand(i)) ||
6298 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6299 isAllZeros = false;
6300 break;
6301 }
6302 if (isAllZeros)
Owen Anderson333c4002009-07-09 23:48:35 +00006303 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006304 Context->getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006305 }
6306 break;
6307
Chris Lattner6970b662005-04-23 15:31:55 +00006308 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006309 // Only fold icmp into the PHI if the phi and fcmp are in the same
6310 // block. If in the same block, we're encouraging jump threading. If
6311 // not, we are just pessimizing the code by making an i1 phi.
6312 if (LHSI->getParent() == I.getParent())
6313 if (Instruction *NV = FoldOpIntoPhi(I))
6314 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006315 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006316 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006317 // If either operand of the select is a constant, we can fold the
6318 // comparison into the select arms, which will cause one to be
6319 // constant folded and the select turned into a bitwise or.
6320 Value *Op1 = 0, *Op2 = 0;
6321 if (LHSI->hasOneUse()) {
6322 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6323 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006324 Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006325 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006326 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006327 LHSI->getOperand(2), RHSC,
6328 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006329 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6330 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006331 Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006332 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006333 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006334 LHSI->getOperand(1), RHSC,
6335 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006336 }
6337 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006338
Chris Lattner6970b662005-04-23 15:31:55 +00006339 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006340 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006341 break;
6342 }
Chris Lattner4802d902007-04-06 18:57:34 +00006343 case Instruction::Malloc:
6344 // If we have (malloc != null), and if the malloc has a single use, we
6345 // can assume it is successful and remove the malloc.
6346 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6347 AddToWorkList(LHSI);
Owen Andersond672ecb2009-07-03 00:17:18 +00006348 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006349 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006350 }
6351 break;
6352 }
Chris Lattner6970b662005-04-23 15:31:55 +00006353 }
6354
Reid Spencere4d87aa2006-12-23 06:05:41 +00006355 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006356 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006357 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006358 return NI;
6359 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006360 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6361 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006362 return NI;
6363
Reid Spencere4d87aa2006-12-23 06:05:41 +00006364 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006365 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6366 // now.
6367 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6368 if (isa<PointerType>(Op0->getType()) &&
6369 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006370 // We keep moving the cast from the left operand over to the right
6371 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006372 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006373
Chris Lattner57d86372007-01-06 01:45:59 +00006374 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6375 // so eliminate it as well.
6376 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6377 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006378
Chris Lattnerde90b762003-11-03 04:25:02 +00006379 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006380 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006381 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006382 Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006383 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006384 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006385 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006386 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006387 }
Owen Anderson333c4002009-07-09 23:48:35 +00006388 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006389 }
Chris Lattner57d86372007-01-06 01:45:59 +00006390 }
6391
6392 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006393 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006394 // This comes up when you have code like
6395 // int X = A < B;
6396 // if (X) ...
6397 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006398 // with a constant or another cast from the same type.
6399 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006400 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006401 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006402 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006403
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006404 // See if it's the same type of instruction on the left and right.
6405 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6406 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006407 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006408 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006409 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006410 default: break;
6411 case Instruction::Add:
6412 case Instruction::Sub:
6413 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006414 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Owen Anderson333c4002009-07-09 23:48:35 +00006415 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006416 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006417 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6418 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6419 if (CI->getValue().isSignBit()) {
6420 ICmpInst::Predicate Pred = I.isSignedPredicate()
6421 ? I.getUnsignedPredicate()
6422 : I.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006423 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006424 Op1I->getOperand(0));
6425 }
6426
6427 if (CI->getValue().isMaxSignedValue()) {
6428 ICmpInst::Predicate Pred = I.isSignedPredicate()
6429 ? I.getUnsignedPredicate()
6430 : I.getSignedPredicate();
6431 Pred = I.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006432 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006433 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006434 }
6435 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006436 break;
6437 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006438 if (!I.isEquality())
6439 break;
6440
Nick Lewycky5d52c452008-08-21 05:56:10 +00006441 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6442 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6443 // Mask = -1 >> count-trailing-zeros(Cst).
6444 if (!CI->isZero() && !CI->isOne()) {
6445 const APInt &AP = CI->getValue();
Owen Andersond672ecb2009-07-03 00:17:18 +00006446 ConstantInt *Mask = Context->getConstantInt(
Nick Lewycky5d52c452008-08-21 05:56:10 +00006447 APInt::getLowBitsSet(AP.getBitWidth(),
6448 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006449 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006450 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6451 Mask);
6452 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6453 Mask);
6454 InsertNewInstBefore(And1, I);
6455 InsertNewInstBefore(And2, I);
Owen Anderson333c4002009-07-09 23:48:35 +00006456 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006457 }
6458 }
6459 break;
6460 }
6461 }
6462 }
6463 }
6464
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006465 // ~x < ~y --> y < x
6466 { Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006467 if (match(Op0, m_Not(m_Value(A)), *Context) &&
6468 match(Op1, m_Not(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006469 return new ICmpInst(*Context, I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006470 }
6471
Chris Lattner65b72ba2006-09-18 04:22:48 +00006472 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006473 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006474
6475 // -x == -y --> x == y
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006476 if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6477 match(Op1, m_Neg(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006478 return new ICmpInst(*Context, I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006479
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006480 if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006481 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6482 Value *OtherVal = A == Op1 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006483 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006484 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006485 }
6486
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006487 if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006488 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006489 ConstantInt *C1, *C2;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006490 if (match(B, m_ConstantInt(C1), *Context) &&
6491 match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006492 Constant *NC =
6493 Context->getConstantInt(C1->getValue() ^ C2->getValue());
Chris Lattnercb504b92008-11-16 05:38:51 +00006494 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Owen Anderson333c4002009-07-09 23:48:35 +00006495 return new ICmpInst(*Context, I.getPredicate(), A,
Chris Lattnercb504b92008-11-16 05:38:51 +00006496 InsertNewInstBefore(Xor, I));
6497 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006498
6499 // A^B == A^D -> B == D
Owen Anderson333c4002009-07-09 23:48:35 +00006500 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6501 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6502 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6503 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006504 }
6505 }
6506
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006507 if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006508 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006509 // A == (A^B) -> B == 0
6510 Value *OtherVal = A == Op0 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006511 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006512 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006513 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006514
6515 // (A-B) == A -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006516 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006517 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006518 Context->getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006519
6520 // A == (A-B) -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006521 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006522 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006523 Context->getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006524
Chris Lattner9c2328e2006-11-14 06:06:06 +00006525 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6526 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006527 match(Op0, m_And(m_Value(A), m_Value(B)), *Context) &&
6528 match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006529 Value *X = 0, *Y = 0, *Z = 0;
6530
6531 if (A == C) {
6532 X = B; Y = D; Z = A;
6533 } else if (A == D) {
6534 X = B; Y = C; Z = A;
6535 } else if (B == C) {
6536 X = A; Y = D; Z = B;
6537 } else if (B == D) {
6538 X = A; Y = C; Z = B;
6539 }
6540
6541 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006542 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6543 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006544 I.setOperand(0, Op1);
Owen Andersond672ecb2009-07-03 00:17:18 +00006545 I.setOperand(1, Context->getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006546 return &I;
6547 }
6548 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006549 }
Chris Lattner7e708292002-06-25 16:13:24 +00006550 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006551}
6552
Chris Lattner562ef782007-06-20 23:46:26 +00006553
6554/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6555/// and CmpRHS are both known to be integer constants.
6556Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6557 ConstantInt *DivRHS) {
6558 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6559 const APInt &CmpRHSV = CmpRHS->getValue();
6560
6561 // FIXME: If the operand types don't match the type of the divide
6562 // then don't attempt this transform. The code below doesn't have the
6563 // logic to deal with a signed divide and an unsigned compare (and
6564 // vice versa). This is because (x /s C1) <s C2 produces different
6565 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6566 // (x /u C1) <u C2. Simply casting the operands and result won't
6567 // work. :( The if statement below tests that condition and bails
6568 // if it finds it.
6569 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6570 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6571 return 0;
6572 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006573 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006574 if (DivIsSigned && DivRHS->isAllOnesValue())
6575 return 0; // The overflow computation also screws up here
6576 if (DivRHS->isOne())
6577 return 0; // Not worth bothering, and eliminates some funny cases
6578 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006579
6580 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6581 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6582 // C2 (CI). By solving for X we can turn this into a range check
6583 // instead of computing a divide.
Owen Andersond672ecb2009-07-03 00:17:18 +00006584 Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006585
6586 // Determine if the product overflows by seeing if the product is
6587 // not equal to the divide. Make sure we do the same kind of divide
6588 // as in the LHS instruction that we're folding.
Owen Andersond672ecb2009-07-03 00:17:18 +00006589 bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6590 Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006591
6592 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006593 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006594
Chris Lattner1dbfd482007-06-21 18:11:19 +00006595 // Figure out the interval that is being checked. For example, a comparison
6596 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6597 // Compute this interval based on the constants involved and the signedness of
6598 // the compare/divide. This computes a half-open interval, keeping track of
6599 // whether either value in the interval overflows. After analysis each
6600 // overflow variable is set to 0 if it's corresponding bound variable is valid
6601 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6602 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006603 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006604
Chris Lattner562ef782007-06-20 23:46:26 +00006605 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006606 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006607 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006608 HiOverflow = LoOverflow = ProdOV;
6609 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006610 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006611 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006612 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006613 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00006614 LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS,
6615 Context)));
Chris Lattner562ef782007-06-20 23:46:26 +00006616 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006617 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006618 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6619 HiOverflow = LoOverflow = ProdOV;
6620 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006621 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006622 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006623 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006624 HiBound = AddOne(Prod, Context);
Chris Lattnera6321b42008-10-11 22:55:00 +00006625 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6626 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006627 ConstantInt* DivNeg =
6628 cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6629 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006630 true) ? -1 : 0;
6631 }
Chris Lattner562ef782007-06-20 23:46:26 +00006632 }
Dan Gohman76491272008-02-13 22:09:18 +00006633 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006634 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006635 // e.g. X/-5 op 0 --> [-4, 5)
Owen Andersond672ecb2009-07-03 00:17:18 +00006636 LoBound = AddOne(DivRHS, Context);
6637 HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006638 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6639 HiOverflow = 1; // [INTMIN+1, overflow)
6640 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6641 }
Dan Gohman76491272008-02-13 22:09:18 +00006642 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006643 // e.g. X/-5 op 3 --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006644 HiBound = AddOne(Prod, Context);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006645 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006646 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006647 LoOverflow = AddWithOverflow(LoBound, HiBound,
6648 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006649 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006650 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6651 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006652 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006653 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006654 }
6655
Chris Lattner1dbfd482007-06-21 18:11:19 +00006656 // Dividing by a negative swaps the condition. LT <-> GT
6657 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006658 }
6659
6660 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006661 switch (Pred) {
Torok Edwinc25e7582009-07-11 20:10:48 +00006662 default: LLVM_UNREACHABLE("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006663 case ICmpInst::ICMP_EQ:
6664 if (LoOverflow && HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006665 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattner562ef782007-06-20 23:46:26 +00006666 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006667 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006668 ICmpInst::ICMP_UGE, X, LoBound);
6669 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006670 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006671 ICmpInst::ICMP_ULT, X, HiBound);
6672 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006673 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006674 case ICmpInst::ICMP_NE:
6675 if (LoOverflow && HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006676 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner562ef782007-06-20 23:46:26 +00006677 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006678 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006679 ICmpInst::ICMP_ULT, X, LoBound);
6680 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006681 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006682 ICmpInst::ICMP_UGE, X, HiBound);
6683 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006684 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006685 case ICmpInst::ICMP_ULT:
6686 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006687 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006688 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006689 if (LoOverflow == -1) // Low bound is less than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006690 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00006691 return new ICmpInst(*Context, Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006692 case ICmpInst::ICMP_UGT:
6693 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006694 if (HiOverflow == +1) // High bound greater than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006695 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006696 else if (HiOverflow == -1) // High bound less than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006697 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006698 if (Pred == ICmpInst::ICMP_UGT)
Owen Anderson333c4002009-07-09 23:48:35 +00006699 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006700 else
Owen Anderson333c4002009-07-09 23:48:35 +00006701 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006702 }
6703}
6704
6705
Chris Lattner01deb9d2007-04-03 17:43:25 +00006706/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6707///
6708Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6709 Instruction *LHSI,
6710 ConstantInt *RHS) {
6711 const APInt &RHSV = RHS->getValue();
6712
6713 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006714 case Instruction::Trunc:
6715 if (ICI.isEquality() && LHSI->hasOneUse()) {
6716 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6717 // of the high bits truncated out of x are known.
6718 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6719 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6720 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6721 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6722 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6723
6724 // If all the high bits are known, we can do this xform.
6725 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6726 // Pull in the high bits from known-ones set.
6727 APInt NewRHS(RHS->getValue());
6728 NewRHS.zext(SrcBits);
6729 NewRHS |= KnownOne;
Owen Anderson333c4002009-07-09 23:48:35 +00006730 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006731 Context->getConstantInt(NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006732 }
6733 }
6734 break;
6735
Duncan Sands0091bf22007-04-04 06:42:45 +00006736 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006737 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6738 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6739 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006740 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6741 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006742 Value *CompareVal = LHSI->getOperand(0);
6743
6744 // If the sign bit of the XorCST is not set, there is no change to
6745 // the operation, just stop using the Xor.
6746 if (!XorCST->getValue().isNegative()) {
6747 ICI.setOperand(0, CompareVal);
6748 AddToWorkList(LHSI);
6749 return &ICI;
6750 }
6751
6752 // Was the old condition true if the operand is positive?
6753 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6754
6755 // If so, the new one isn't.
6756 isTrueIfPositive ^= true;
6757
6758 if (isTrueIfPositive)
Owen Anderson333c4002009-07-09 23:48:35 +00006759 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006760 SubOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006761 else
Owen Anderson333c4002009-07-09 23:48:35 +00006762 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006763 AddOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006764 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006765
6766 if (LHSI->hasOneUse()) {
6767 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6768 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6769 const APInt &SignBit = XorCST->getValue();
6770 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6771 ? ICI.getUnsignedPredicate()
6772 : ICI.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006773 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006774 Context->getConstantInt(RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006775 }
6776
6777 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006778 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006779 const APInt &NotSignBit = XorCST->getValue();
6780 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6781 ? ICI.getUnsignedPredicate()
6782 : ICI.getSignedPredicate();
6783 Pred = ICI.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006784 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006785 Context->getConstantInt(RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006786 }
6787 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006788 }
6789 break;
6790 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6791 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6792 LHSI->getOperand(0)->hasOneUse()) {
6793 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6794
6795 // If the LHS is an AND of a truncating cast, we can widen the
6796 // and/compare to be the input width without changing the value
6797 // produced, eliminating a cast.
6798 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6799 // We can do this transformation if either the AND constant does not
6800 // have its sign bit set or if it is an equality comparison.
6801 // Extending a relational comparison when we're checking the sign
6802 // bit would not work.
6803 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006804 (ICI.isEquality() ||
6805 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006806 uint32_t BitWidth =
6807 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6808 APInt NewCST = AndCST->getValue();
6809 NewCST.zext(BitWidth);
6810 APInt NewCI = RHSV;
6811 NewCI.zext(BitWidth);
6812 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006813 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006814 Context->getConstantInt(NewCST),LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006815 InsertNewInstBefore(NewAnd, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006816 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
Owen Andersond672ecb2009-07-03 00:17:18 +00006817 Context->getConstantInt(NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006818 }
6819 }
6820
6821 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6822 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6823 // happens a LOT in code produced by the C front-end, for bitfield
6824 // access.
6825 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6826 if (Shift && !Shift->isShift())
6827 Shift = 0;
6828
6829 ConstantInt *ShAmt;
6830 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6831 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6832 const Type *AndTy = AndCST->getType(); // Type of the and.
6833
6834 // We can fold this as long as we can't shift unknown bits
6835 // into the mask. This can only happen with signed shift
6836 // rights, as they sign-extend.
6837 if (ShAmt) {
6838 bool CanFold = Shift->isLogicalShift();
6839 if (!CanFold) {
6840 // To test for the bad case of the signed shr, see if any
6841 // of the bits shifted in could be tested after the mask.
6842 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6843 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6844
6845 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6846 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6847 AndCST->getValue()) == 0)
6848 CanFold = true;
6849 }
6850
6851 if (CanFold) {
6852 Constant *NewCst;
6853 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006854 NewCst = Context->getConstantExprLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006855 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006856 NewCst = Context->getConstantExprShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006857
6858 // Check to see if we are shifting out any of the bits being
6859 // compared.
Owen Andersond672ecb2009-07-03 00:17:18 +00006860 if (Context->getConstantExpr(Shift->getOpcode(),
6861 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006862 // If we shifted bits out, the fold is not going to work out.
6863 // As a special case, check to see if this means that the
6864 // result is always true or false now.
6865 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersond672ecb2009-07-03 00:17:18 +00006866 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006867 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersond672ecb2009-07-03 00:17:18 +00006868 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006869 } else {
6870 ICI.setOperand(1, NewCst);
6871 Constant *NewAndCST;
6872 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006873 NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006874 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006875 NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006876 LHSI->setOperand(1, NewAndCST);
6877 LHSI->setOperand(0, Shift->getOperand(0));
6878 AddToWorkList(Shift); // Shift is dead.
6879 AddUsesToWorkList(ICI);
6880 return &ICI;
6881 }
6882 }
6883 }
6884
6885 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6886 // preferable because it allows the C<<Y expression to be hoisted out
6887 // of a loop if Y is invariant and X is not.
6888 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006889 ICI.isEquality() && !Shift->isArithmeticShift() &&
6890 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006891 // Compute C << Y.
6892 Value *NS;
6893 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006894 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006895 Shift->getOperand(1), "tmp");
6896 } else {
6897 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006898 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006899 Shift->getOperand(1), "tmp");
6900 }
6901 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6902
6903 // Compute X & (C << Y).
6904 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006905 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006906 InsertNewInstBefore(NewAnd, ICI);
6907
6908 ICI.setOperand(0, NewAnd);
6909 return &ICI;
6910 }
6911 }
6912 break;
6913
Chris Lattnera0141b92007-07-15 20:42:37 +00006914 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6915 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6916 if (!ShAmt) break;
6917
6918 uint32_t TypeBits = RHSV.getBitWidth();
6919
6920 // Check that the shift amount is in range. If not, don't perform
6921 // undefined shifts. When the shift is visited it will be
6922 // simplified.
6923 if (ShAmt->uge(TypeBits))
6924 break;
6925
6926 if (ICI.isEquality()) {
6927 // If we are comparing against bits always shifted out, the
6928 // comparison cannot succeed.
6929 Constant *Comp =
Owen Andersond672ecb2009-07-03 00:17:18 +00006930 Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6931 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006932 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6933 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersond672ecb2009-07-03 00:17:18 +00006934 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006935 return ReplaceInstUsesWith(ICI, Cst);
6936 }
6937
6938 if (LHSI->hasOneUse()) {
6939 // Otherwise strength reduce the shift into an and.
6940 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6941 Constant *Mask =
Owen Andersond672ecb2009-07-03 00:17:18 +00006942 Context->getConstantInt(APInt::getLowBitsSet(TypeBits,
6943 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006944
Chris Lattnera0141b92007-07-15 20:42:37 +00006945 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006946 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006947 Mask, LHSI->getName()+".mask");
6948 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006949 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00006950 Context->getConstantInt(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006951 }
6952 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006953
6954 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6955 bool TrueIfSigned = false;
6956 if (LHSI->hasOneUse() &&
6957 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6958 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersond672ecb2009-07-03 00:17:18 +00006959 Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006960 (TypeBits-ShAmt->getZExtValue()-1));
6961 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006962 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006963 Mask, LHSI->getName()+".mask");
6964 Value *And = InsertNewInstBefore(AndI, ICI);
6965
Owen Anderson333c4002009-07-09 23:48:35 +00006966 return new ICmpInst(*Context,
6967 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersond672ecb2009-07-03 00:17:18 +00006968 And, Context->getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006969 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006970 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006971 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006972
6973 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006974 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006975 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006976 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006977 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006978
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006979 // Check that the shift amount is in range. If not, don't perform
6980 // undefined shifts. When the shift is visited it will be
6981 // simplified.
6982 uint32_t TypeBits = RHSV.getBitWidth();
6983 if (ShAmt->uge(TypeBits))
6984 break;
6985
6986 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006987
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006988 // If we are comparing against bits always shifted out, the
6989 // comparison cannot succeed.
6990 APInt Comp = RHSV << ShAmtVal;
6991 if (LHSI->getOpcode() == Instruction::LShr)
6992 Comp = Comp.lshr(ShAmtVal);
6993 else
6994 Comp = Comp.ashr(ShAmtVal);
6995
6996 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6997 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersond672ecb2009-07-03 00:17:18 +00006998 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006999 return ReplaceInstUsesWith(ICI, Cst);
7000 }
7001
7002 // Otherwise, check to see if the bits shifted out are known to be zero.
7003 // If so, we can compare against the unshifted value:
7004 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007005 if (LHSI->hasOneUse() &&
7006 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007007 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Owen Anderson333c4002009-07-09 23:48:35 +00007008 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007009 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007010 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007011
Evan Chengf30752c2008-04-23 00:38:06 +00007012 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007013 // Otherwise strength reduce the shift into an and.
7014 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00007015 Constant *Mask = Context->getConstantInt(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007016
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007017 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007018 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007019 Mask, LHSI->getName()+".mask");
7020 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007021 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00007022 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007023 }
7024 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007025 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007026
7027 case Instruction::SDiv:
7028 case Instruction::UDiv:
7029 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7030 // Fold this div into the comparison, producing a range check.
7031 // Determine, based on the divide type, what the range is being
7032 // checked. If there is an overflow on the low or high side, remember
7033 // it, otherwise compute the range [low, hi) bounding the new value.
7034 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007035 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7036 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7037 DivRHS))
7038 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007039 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007040
7041 case Instruction::Add:
7042 // Fold: icmp pred (add, X, C1), C2
7043
7044 if (!ICI.isEquality()) {
7045 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7046 if (!LHSC) break;
7047 const APInt &LHSV = LHSC->getValue();
7048
7049 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7050 .subtract(LHSV);
7051
7052 if (ICI.isSignedPredicate()) {
7053 if (CR.getLower().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007054 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007055 Context->getConstantInt(CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007056 } else if (CR.getUpper().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007057 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007058 Context->getConstantInt(CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007059 }
7060 } else {
7061 if (CR.getLower().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007062 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007063 Context->getConstantInt(CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007064 } else if (CR.getUpper().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007065 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007066 Context->getConstantInt(CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007067 }
7068 }
7069 }
7070 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007071 }
7072
7073 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7074 if (ICI.isEquality()) {
7075 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7076
7077 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7078 // the second operand is a constant, simplify a bit.
7079 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7080 switch (BO->getOpcode()) {
7081 case Instruction::SRem:
7082 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7083 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7084 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7085 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7086 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007087 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007088 BO->getName());
7089 InsertNewInstBefore(NewRem, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007090 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
Owen Andersond672ecb2009-07-03 00:17:18 +00007091 Context->getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007092 }
7093 }
7094 break;
7095 case Instruction::Add:
7096 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7097 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7098 if (BO->hasOneUse())
Owen Anderson333c4002009-07-09 23:48:35 +00007099 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007100 Context->getConstantExprSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007101 } else if (RHSV == 0) {
7102 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7103 // efficiently invertible, or if the add has just this one use.
7104 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7105
Owen Andersond672ecb2009-07-03 00:17:18 +00007106 if (Value *NegVal = dyn_castNegVal(BOp1, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007107 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
Owen Andersond672ecb2009-07-03 00:17:18 +00007108 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007109 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007110 else if (BO->hasOneUse()) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00007111 Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007112 InsertNewInstBefore(Neg, ICI);
7113 Neg->takeName(BO);
Owen Anderson333c4002009-07-09 23:48:35 +00007114 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007115 }
7116 }
7117 break;
7118 case Instruction::Xor:
7119 // For the xor case, we can xor two constants together, eliminating
7120 // the explicit xor.
7121 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Owen Anderson333c4002009-07-09 23:48:35 +00007122 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007123 Context->getConstantExprXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007124
7125 // FALLTHROUGH
7126 case Instruction::Sub:
7127 // Replace (([sub|xor] A, B) != 0) with (A != B)
7128 if (RHSV == 0)
Owen Anderson333c4002009-07-09 23:48:35 +00007129 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007130 BO->getOperand(1));
7131 break;
7132
7133 case Instruction::Or:
7134 // If bits are being or'd in that are not present in the constant we
7135 // are comparing against, then the comparison could never succeed!
7136 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007137 Constant *NotCI = Context->getConstantExprNot(RHS);
7138 if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7139 return ReplaceInstUsesWith(ICI,
7140 Context->getConstantInt(Type::Int1Ty,
7141 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007142 }
7143 break;
7144
7145 case Instruction::And:
7146 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7147 // If bits are being compared against that are and'd out, then the
7148 // comparison can never succeed!
7149 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007150 return ReplaceInstUsesWith(ICI,
7151 Context->getConstantInt(Type::Int1Ty,
7152 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007153
7154 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7155 if (RHS == BOC && RHSV.isPowerOf2())
Owen Anderson333c4002009-07-09 23:48:35 +00007156 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007157 ICmpInst::ICMP_NE, LHSI,
Owen Andersond672ecb2009-07-03 00:17:18 +00007158 Context->getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007159
7160 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007161 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007162 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007163 Constant *Zero = Context->getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007164 ICmpInst::Predicate pred = isICMP_NE ?
7165 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Owen Anderson333c4002009-07-09 23:48:35 +00007166 return new ICmpInst(*Context, pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007167 }
7168
7169 // ((X & ~7) == 0) --> X < 8
7170 if (RHSV == 0 && isHighOnes(BOC)) {
7171 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007172 Constant *NegX = Context->getConstantExprNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007173 ICmpInst::Predicate pred = isICMP_NE ?
7174 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Owen Anderson333c4002009-07-09 23:48:35 +00007175 return new ICmpInst(*Context, pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007176 }
7177 }
7178 default: break;
7179 }
7180 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7181 // Handle icmp {eq|ne} <intrinsic>, intcst.
7182 if (II->getIntrinsicID() == Intrinsic::bswap) {
7183 AddToWorkList(II);
7184 ICI.setOperand(0, II->getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007185 ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007186 return &ICI;
7187 }
7188 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007189 }
7190 return 0;
7191}
7192
7193/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7194/// We only handle extending casts so far.
7195///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007196Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7197 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007198 Value *LHSCIOp = LHSCI->getOperand(0);
7199 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007200 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007201 Value *RHSCIOp;
7202
Chris Lattner8c756c12007-05-05 22:41:33 +00007203 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7204 // integer type is the same size as the pointer type.
7205 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7206 getTargetData().getPointerSizeInBits() ==
7207 cast<IntegerType>(DestTy)->getBitWidth()) {
7208 Value *RHSOp = 0;
7209 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007210 RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007211 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7212 RHSOp = RHSC->getOperand(0);
7213 // If the pointer types don't match, insert a bitcast.
7214 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007215 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007216 }
7217
7218 if (RHSOp)
Owen Anderson333c4002009-07-09 23:48:35 +00007219 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007220 }
7221
7222 // The code below only handles extension cast instructions, so far.
7223 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007224 if (LHSCI->getOpcode() != Instruction::ZExt &&
7225 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007226 return 0;
7227
Reid Spencere4d87aa2006-12-23 06:05:41 +00007228 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7229 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007230
Reid Spencere4d87aa2006-12-23 06:05:41 +00007231 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007232 // Not an extension from the same type?
7233 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007234 if (RHSCIOp->getType() != LHSCIOp->getType())
7235 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007236
Nick Lewycky4189a532008-01-28 03:48:02 +00007237 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007238 // and the other is a zext), then we can't handle this.
7239 if (CI->getOpcode() != LHSCI->getOpcode())
7240 return 0;
7241
Nick Lewycky4189a532008-01-28 03:48:02 +00007242 // Deal with equality cases early.
7243 if (ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007244 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007245
7246 // A signed comparison of sign extended values simplifies into a
7247 // signed comparison.
7248 if (isSignedCmp && isSignedExt)
Owen Anderson333c4002009-07-09 23:48:35 +00007249 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007250
7251 // The other three cases all fold into an unsigned comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00007252 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007253 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007254
Reid Spencere4d87aa2006-12-23 06:05:41 +00007255 // If we aren't dealing with a constant on the RHS, exit early
7256 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7257 if (!CI)
7258 return 0;
7259
7260 // Compute the constant that would happen if we truncated to SrcTy then
7261 // reextended to DestTy.
Owen Andersond672ecb2009-07-03 00:17:18 +00007262 Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7263 Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7264 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007265
7266 // If the re-extended constant didn't change...
7267 if (Res2 == CI) {
7268 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7269 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007270 // %A = sext i16 %X to i32
7271 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007272 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007273 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007274 // because %A may have negative value.
7275 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007276 // However, we allow this when the compare is EQ/NE, because they are
7277 // signless.
7278 if (isSignedExt == isSignedCmp || ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007279 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007280 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007281 }
7282
7283 // The re-extended constant changed so the constant cannot be represented
7284 // in the shorter type. Consequently, we cannot emit a simple comparison.
7285
7286 // First, handle some easy cases. We know the result cannot be equal at this
7287 // point so handle the ICI.isEquality() cases
7288 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersond672ecb2009-07-03 00:17:18 +00007289 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007290 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersond672ecb2009-07-03 00:17:18 +00007291 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007292
7293 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7294 // should have been folded away previously and not enter in here.
7295 Value *Result;
7296 if (isSignedCmp) {
7297 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007298 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00007299 Result = Context->getConstantIntFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007300 else
Owen Andersond672ecb2009-07-03 00:17:18 +00007301 Result = Context->getConstantIntTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007302 } else {
7303 // We're performing an unsigned comparison.
7304 if (isSignedExt) {
7305 // We're performing an unsigned comp with a sign extended value.
7306 // This is true if the input is >= 0. [aka >s -1]
Owen Anderson73c6b712009-07-13 20:58:05 +00007307 Constant *NegOne = Context->getAllOnesValue(SrcTy);
Owen Anderson333c4002009-07-09 23:48:35 +00007308 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7309 LHSCIOp, NegOne, ICI.getName()), ICI);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007310 } else {
7311 // Unsigned extend & unsigned compare -> always true.
Owen Andersond672ecb2009-07-03 00:17:18 +00007312 Result = Context->getConstantIntTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007313 }
7314 }
7315
7316 // Finally, return the value computed.
7317 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007318 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007319 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007320
7321 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7322 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7323 "ICmp should be folded!");
7324 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00007325 return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
Owen Anderson73c6b712009-07-13 20:58:05 +00007326 return BinaryOperator::CreateNot(*Context, Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007327}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007328
Reid Spencer832254e2007-02-02 02:16:23 +00007329Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7330 return commonShiftTransforms(I);
7331}
7332
7333Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7334 return commonShiftTransforms(I);
7335}
7336
7337Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007338 if (Instruction *R = commonShiftTransforms(I))
7339 return R;
7340
7341 Value *Op0 = I.getOperand(0);
7342
7343 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7344 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7345 if (CSI->isAllOnesValue())
7346 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007347
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007348 // See if we can turn a signed shr into an unsigned shr.
7349 if (MaskedValueIsZero(Op0,
7350 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7351 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7352
7353 // Arithmetic shifting an all-sign-bit value is a no-op.
7354 unsigned NumSignBits = ComputeNumSignBits(Op0);
7355 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7356 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007357
Chris Lattner348f6652007-12-06 01:59:46 +00007358 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007359}
7360
7361Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7362 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007363 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007364
7365 // shl X, 0 == X and shr X, 0 == X
7366 // shl 0, X == 0 and shr 0, X == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007367 if (Op1 == Context->getNullValue(Op1->getType()) ||
7368 Op0 == Context->getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007369 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007370
Reid Spencere4d87aa2006-12-23 06:05:41 +00007371 if (isa<UndefValue>(Op0)) {
7372 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007373 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007374 else // undef << X -> 0, undef >>u X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007375 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007376 }
7377 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007378 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7379 return ReplaceInstUsesWith(I, Op0);
7380 else // X << undef, X >>u undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007381 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007382 }
7383
Dan Gohman9004c8a2009-05-21 02:28:33 +00007384 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007385 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007386 return &I;
7387
Chris Lattner2eefe512004-04-09 19:05:30 +00007388 // Try to fold constant and into select arguments.
7389 if (isa<Constant>(Op0))
7390 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007391 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007392 return R;
7393
Reid Spencerb83eb642006-10-20 07:07:24 +00007394 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007395 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7396 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007397 return 0;
7398}
7399
Reid Spencerb83eb642006-10-20 07:07:24 +00007400Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007401 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007402 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007403
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007404 // See if we can simplify any instructions used by the instruction whose sole
7405 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007406 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007407
Dan Gohmana119de82009-06-14 23:30:43 +00007408 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7409 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007410 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007411 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007412 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007413 return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007414 else {
Owen Andersond672ecb2009-07-03 00:17:18 +00007415 I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007416 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007417 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007418 }
7419
7420 // ((X*C1) << C2) == (X * (C1 << C2))
7421 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7422 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7423 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007424 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007425 Context->getConstantExprShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007426
7427 // Try to fold constant and into select arguments.
7428 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7429 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7430 return R;
7431 if (isa<PHINode>(Op0))
7432 if (Instruction *NV = FoldOpIntoPhi(I))
7433 return NV;
7434
Chris Lattner8999dd32007-12-22 09:07:47 +00007435 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7436 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7437 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7438 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7439 // place. Don't try to do this transformation in this case. Also, we
7440 // require that the input operand is a shift-by-constant so that we have
7441 // confidence that the shifts will get folded together. We could do this
7442 // xform in more cases, but it is unlikely to be profitable.
7443 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7444 isa<ConstantInt>(TrOp->getOperand(1))) {
7445 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersond672ecb2009-07-03 00:17:18 +00007446 Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007447 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007448 I.getName());
7449 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7450
7451 // For logical shifts, the truncation has the effect of making the high
7452 // part of the register be zeros. Emulate this by inserting an AND to
7453 // clear the top bits as needed. This 'and' will usually be zapped by
7454 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007455 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7456 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007457 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7458
7459 // The mask we constructed says what the trunc would do if occurring
7460 // between the shifts. We want to know the effect *after* the second
7461 // shift. We know that it is a logical shift by a constant, so adjust the
7462 // mask as appropriate.
7463 if (I.getOpcode() == Instruction::Shl)
7464 MaskV <<= Op1->getZExtValue();
7465 else {
7466 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7467 MaskV = MaskV.lshr(Op1->getZExtValue());
7468 }
7469
Owen Andersond672ecb2009-07-03 00:17:18 +00007470 Instruction *And =
7471 BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV),
7472 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007473 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7474
7475 // Return the value truncated to the interesting size.
7476 return new TruncInst(And, I.getType());
7477 }
7478 }
7479
Chris Lattner4d5542c2006-01-06 07:12:35 +00007480 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007481 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7482 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7483 Value *V1, *V2;
7484 ConstantInt *CC;
7485 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007486 default: break;
7487 case Instruction::Add:
7488 case Instruction::And:
7489 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007490 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007491 // These operators commute.
7492 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007493 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007494 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7495 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007496 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007497 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007498 Op0BO->getName());
7499 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007500 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007501 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007502 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007503 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007504 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersond672ecb2009-07-03 00:17:18 +00007505 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng90b96812007-03-30 05:45:18 +00007506 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007507 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007508
Chris Lattner150f12a2005-09-18 06:30:59 +00007509 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007510 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007511 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007512 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007513 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007514 m_ConstantInt(CC)), *Context) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007515 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007516 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007517 Op0BO->getOperand(0), Op1,
7518 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007519 InsertNewInstBefore(YS, I); // (Y << C)
7520 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007521 BinaryOperator::CreateAnd(V1,
7522 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007523 V1->getName()+".mask");
7524 InsertNewInstBefore(XM, I); // X & (CC << C)
7525
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007526 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007527 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007528 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007529
Reid Spencera07cb7d2007-02-02 14:41:37 +00007530 // FALL THROUGH.
7531 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007532 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007533 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007534 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7535 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007536 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007537 Op0BO->getOperand(1), Op1,
7538 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007539 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007540 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007541 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007542 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007543 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007544 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersond672ecb2009-07-03 00:17:18 +00007545 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng90b96812007-03-30 05:45:18 +00007546 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007547 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007548
Chris Lattner13d4ab42006-05-31 21:14:00 +00007549 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007550 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7551 match(Op0BO->getOperand(0),
7552 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007553 m_ConstantInt(CC)), *Context) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007554 cast<BinaryOperator>(Op0BO->getOperand(0))
7555 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007556 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007557 Op0BO->getOperand(1), Op1,
7558 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007559 InsertNewInstBefore(YS, I); // (Y << C)
7560 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007561 BinaryOperator::CreateAnd(V1,
7562 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007563 V1->getName()+".mask");
7564 InsertNewInstBefore(XM, I); // X & (CC << C)
7565
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007566 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007567 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007568
Chris Lattner11021cb2005-09-18 05:12:10 +00007569 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007570 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007571 }
7572
7573
7574 // If the operand is an bitwise operator with a constant RHS, and the
7575 // shift is the only use, we can pull it out of the shift.
7576 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7577 bool isValid = true; // Valid only for And, Or, Xor
7578 bool highBitSet = false; // Transform if high bit of constant set?
7579
7580 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007581 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007582 case Instruction::Add:
7583 isValid = isLeftShift;
7584 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007585 case Instruction::Or:
7586 case Instruction::Xor:
7587 highBitSet = false;
7588 break;
7589 case Instruction::And:
7590 highBitSet = true;
7591 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007592 }
7593
7594 // If this is a signed shift right, and the high bit is modified
7595 // by the logical operation, do not perform the transformation.
7596 // The highBitSet boolean indicates the value of the high bit of
7597 // the constant which would cause it to be modified for this
7598 // operation.
7599 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007600 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007601 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007602
7603 if (isValid) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007604 Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007605
7606 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007607 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007608 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007609 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007610
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007611 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007612 NewRHS);
7613 }
7614 }
7615 }
7616 }
7617
Chris Lattnerad0124c2006-01-06 07:52:12 +00007618 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007619 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7620 if (ShiftOp && !ShiftOp->isShift())
7621 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007622
Reid Spencerb83eb642006-10-20 07:07:24 +00007623 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007624 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007625 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7626 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007627 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7628 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7629 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007630
Zhou Sheng4351c642007-04-02 08:20:41 +00007631 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007632
7633 const IntegerType *Ty = cast<IntegerType>(I.getType());
7634
7635 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007636 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007637 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7638 // saturates.
7639 if (AmtSum >= TypeBits) {
7640 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007641 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007642 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7643 }
7644
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007645 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersond672ecb2009-07-03 00:17:18 +00007646 Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007647 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7648 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007649 if (AmtSum >= TypeBits)
Owen Andersond672ecb2009-07-03 00:17:18 +00007650 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007651
Chris Lattnerb87056f2007-02-05 00:57:54 +00007652 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersond672ecb2009-07-03 00:17:18 +00007653 return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007654 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7655 I.getOpcode() == Instruction::LShr) {
7656 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007657 if (AmtSum >= TypeBits)
7658 AmtSum = TypeBits-1;
7659
Chris Lattnerb87056f2007-02-05 00:57:54 +00007660 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007661 BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007662 InsertNewInstBefore(Shift, I);
7663
Zhou Shenge9e03f62007-03-28 15:02:20 +00007664 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007665 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007666 }
7667
Chris Lattnerb87056f2007-02-05 00:57:54 +00007668 // Okay, if we get here, one shift must be left, and the other shift must be
7669 // right. See if the amounts are equal.
7670 if (ShiftAmt1 == ShiftAmt2) {
7671 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7672 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007673 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007674 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007675 }
7676 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7677 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007678 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007679 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007680 }
7681 // We can simplify ((X << C) >>s C) into a trunc + sext.
7682 // NOTE: we could do this for any C, but that would make 'unusual' integer
7683 // types. For now, just stick to ones well-supported by the code
7684 // generators.
7685 const Type *SExtType = 0;
7686 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007687 case 1 :
7688 case 8 :
7689 case 16 :
7690 case 32 :
7691 case 64 :
7692 case 128:
Owen Andersond672ecb2009-07-03 00:17:18 +00007693 SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007694 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007695 default: break;
7696 }
7697 if (SExtType) {
7698 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7699 InsertNewInstBefore(NewTrunc, I);
7700 return new SExtInst(NewTrunc, Ty);
7701 }
7702 // Otherwise, we can't handle it yet.
7703 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007704 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007705
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007706 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007707 if (I.getOpcode() == Instruction::Shl) {
7708 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7709 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007710 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007711 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007712 InsertNewInstBefore(Shift, I);
7713
Reid Spencer55702aa2007-03-25 21:11:44 +00007714 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007715 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007716 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007717
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007718 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007719 if (I.getOpcode() == Instruction::LShr) {
7720 assert(ShiftOp->getOpcode() == Instruction::Shl);
7721 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007722 BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007723 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007724
Reid Spencerd5e30f02007-03-26 17:18:58 +00007725 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007726 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007727 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007728
7729 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7730 } else {
7731 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007732 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007733
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007734 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007735 if (I.getOpcode() == Instruction::Shl) {
7736 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7737 ShiftOp->getOpcode() == Instruction::AShr);
7738 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007739 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersond672ecb2009-07-03 00:17:18 +00007740 Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007741 InsertNewInstBefore(Shift, I);
7742
Reid Spencer55702aa2007-03-25 21:11:44 +00007743 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007744 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007745 }
7746
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007747 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007748 if (I.getOpcode() == Instruction::LShr) {
7749 assert(ShiftOp->getOpcode() == Instruction::Shl);
7750 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007751 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007752 InsertNewInstBefore(Shift, I);
7753
Reid Spencer68d27cf2007-03-26 23:45:51 +00007754 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007755 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007756 }
7757
7758 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007759 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007760 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007761 return 0;
7762}
7763
Chris Lattnera1be5662002-05-02 17:06:02 +00007764
Chris Lattnercfd65102005-10-29 04:36:15 +00007765/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7766/// expression. If so, decompose it, returning some value X, such that Val is
7767/// X*Scale+Offset.
7768///
7769static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007770 int &Offset, LLVMContext *Context) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007771 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007772 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007773 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007774 Scale = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00007775 return Context->getConstantInt(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007776 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7777 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7778 if (I->getOpcode() == Instruction::Shl) {
7779 // This is a value scaled by '1 << the shift amt'.
7780 Scale = 1U << RHS->getZExtValue();
7781 Offset = 0;
7782 return I->getOperand(0);
7783 } else if (I->getOpcode() == Instruction::Mul) {
7784 // This value is scaled by 'RHS'.
7785 Scale = RHS->getZExtValue();
7786 Offset = 0;
7787 return I->getOperand(0);
7788 } else if (I->getOpcode() == Instruction::Add) {
7789 // We have X+C. Check to see if we really have (X*C2)+C1,
7790 // where C1 is divisible by C2.
7791 unsigned SubScale;
7792 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007793 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7794 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007795 Offset += RHS->getZExtValue();
7796 Scale = SubScale;
7797 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007798 }
7799 }
7800 }
7801
7802 // Otherwise, we can't look past this.
7803 Scale = 1;
7804 Offset = 0;
7805 return Val;
7806}
7807
7808
Chris Lattnerb3f83972005-10-24 06:03:58 +00007809/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7810/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007811Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007812 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007813 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007814
Chris Lattnerb53c2382005-10-24 06:22:12 +00007815 // Remove any uses of AI that are dead.
7816 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007817
Chris Lattnerb53c2382005-10-24 06:22:12 +00007818 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7819 Instruction *User = cast<Instruction>(*UI++);
7820 if (isInstructionTriviallyDead(User)) {
7821 while (UI != E && *UI == User)
7822 ++UI; // If this instruction uses AI more than once, don't break UI.
7823
Chris Lattnerb53c2382005-10-24 06:22:12 +00007824 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007825 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007826 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007827 }
7828 }
7829
Chris Lattnerb3f83972005-10-24 06:03:58 +00007830 // Get the type really allocated and the type casted to.
7831 const Type *AllocElTy = AI.getAllocatedType();
7832 const Type *CastElTy = PTy->getElementType();
7833 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007834
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007835 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7836 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007837 if (CastElTyAlign < AllocElTyAlign) return 0;
7838
Chris Lattner39387a52005-10-24 06:35:18 +00007839 // If the allocation has multiple uses, only promote it if we are strictly
7840 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007841 // same, we open the door to infinite loops of various kinds. (A reference
7842 // from a dbg.declare doesn't count as a use for this purpose.)
7843 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7844 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007845
Duncan Sands777d2302009-05-09 07:06:46 +00007846 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7847 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007848 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007849
Chris Lattner455fcc82005-10-29 03:19:53 +00007850 // See if we can satisfy the modulus by pulling a scale out of the array
7851 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007852 unsigned ArraySizeScale;
7853 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007854 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007855 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7856 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007857
Chris Lattner455fcc82005-10-29 03:19:53 +00007858 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7859 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007860 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7861 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007862
Chris Lattner455fcc82005-10-29 03:19:53 +00007863 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7864 Value *Amt = 0;
7865 if (Scale == 1) {
7866 Amt = NumElements;
7867 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007868 // If the allocation size is constant, form a constant mul expression
Owen Andersond672ecb2009-07-03 00:17:18 +00007869 Amt = Context->getConstantInt(Type::Int32Ty, Scale);
Reid Spencerc5b206b2006-12-31 05:48:39 +00007870 if (isa<ConstantInt>(NumElements))
Owen Andersond672ecb2009-07-03 00:17:18 +00007871 Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
Dan Gohman6de29f82009-06-15 22:12:54 +00007872 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007873 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007874 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007875 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007876 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007877 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007878 }
7879
Jeff Cohen86796be2007-04-04 16:58:57 +00007880 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007881 Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007882 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007883 Amt = InsertNewInstBefore(Tmp, AI);
7884 }
7885
Chris Lattnerb3f83972005-10-24 06:03:58 +00007886 AllocationInst *New;
7887 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007888 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007889 else
Chris Lattner6934a042007-02-11 01:23:03 +00007890 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007891 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007892 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007893
Dale Johannesena0a66372009-03-05 00:39:02 +00007894 // If the allocation has one real use plus a dbg.declare, just remove the
7895 // declare.
7896 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7897 EraseInstFromFunction(*DI);
7898 }
7899 // If the allocation has multiple real uses, insert a cast and change all
7900 // things that used it to use the new cast. This will also hack on CI, but it
7901 // will die soon.
7902 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007903 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007904 // New is the allocation instruction, pointer typed. AI is the original
7905 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7906 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007907 InsertNewInstBefore(NewCast, AI);
7908 AI.replaceAllUsesWith(NewCast);
7909 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007910 return ReplaceInstUsesWith(CI, New);
7911}
7912
Chris Lattner70074e02006-05-13 02:06:03 +00007913/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007914/// and return it as type Ty without inserting any new casts and without
7915/// changing the computed value. This is used by code that tries to decide
7916/// whether promoting or shrinking integer operations to wider or smaller types
7917/// will allow us to eliminate a truncate or extend.
7918///
7919/// This is a truncation operation if Ty is smaller than V->getType(), or an
7920/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007921///
7922/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7923/// should return true if trunc(V) can be computed by computing V in the smaller
7924/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7925/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7926/// efficiently truncated.
7927///
7928/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7929/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7930/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007931bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007932 unsigned CastOpc,
7933 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007934 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007935 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007936 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007937
7938 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007939 if (!I) return false;
7940
Dan Gohman6de29f82009-06-15 22:12:54 +00007941 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007942
Chris Lattner951626b2007-08-02 06:11:14 +00007943 // If this is an extension or truncate, we can often eliminate it.
7944 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7945 // If this is a cast from the destination type, we can trivially eliminate
7946 // it, and this will remove a cast overall.
7947 if (I->getOperand(0)->getType() == Ty) {
7948 // If the first operand is itself a cast, and is eliminable, do not count
7949 // this as an eliminable cast. We would prefer to eliminate those two
7950 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007951 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007952 ++NumCastsRemoved;
7953 return true;
7954 }
7955 }
7956
7957 // We can't extend or shrink something that has multiple uses: doing so would
7958 // require duplicating the instruction in general, which isn't profitable.
7959 if (!I->hasOneUse()) return false;
7960
Evan Chengf35fd542009-01-15 17:01:23 +00007961 unsigned Opc = I->getOpcode();
7962 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007963 case Instruction::Add:
7964 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007965 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007966 case Instruction::And:
7967 case Instruction::Or:
7968 case Instruction::Xor:
7969 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007970 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007971 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007972 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007973 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007974
Chris Lattner46b96052006-11-29 07:18:39 +00007975 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007976 // If we are truncating the result of this SHL, and if it's a shift of a
7977 // constant amount, we can always perform a SHL in a smaller type.
7978 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007979 uint32_t BitWidth = Ty->getScalarSizeInBits();
7980 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007981 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007982 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007983 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007984 }
7985 break;
7986 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007987 // If this is a truncate of a logical shr, we can truncate it to a smaller
7988 // lshr iff we know that the bits we would otherwise be shifting in are
7989 // already zeros.
7990 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007991 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7992 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007993 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007994 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007995 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7996 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007997 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007998 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007999 }
8000 }
Chris Lattner46b96052006-11-29 07:18:39 +00008001 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008002 case Instruction::ZExt:
8003 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008004 case Instruction::Trunc:
8005 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008006 // can safely replace it. Note that replacing it does not reduce the number
8007 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008008 if (Opc == CastOpc)
8009 return true;
8010
8011 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008012 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008013 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008014 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008015 case Instruction::Select: {
8016 SelectInst *SI = cast<SelectInst>(I);
8017 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008018 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008019 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008020 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008021 }
Chris Lattner8114b712008-06-18 04:00:49 +00008022 case Instruction::PHI: {
8023 // We can change a phi if we can change all operands.
8024 PHINode *PN = cast<PHINode>(I);
8025 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8026 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008027 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008028 return false;
8029 return true;
8030 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008031 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008032 // TODO: Can handle more cases here.
8033 break;
8034 }
8035
8036 return false;
8037}
8038
8039/// EvaluateInDifferentType - Given an expression that
8040/// CanEvaluateInDifferentType returns true for, actually insert the code to
8041/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008042Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008043 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008044 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +00008045 return Context->getConstantExprIntegerCast(C, Ty,
8046 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008047
8048 // Otherwise, it must be an instruction.
8049 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008050 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008051 unsigned Opc = I->getOpcode();
8052 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008053 case Instruction::Add:
8054 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008055 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008056 case Instruction::And:
8057 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008058 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008059 case Instruction::AShr:
8060 case Instruction::LShr:
8061 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008062 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008063 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008064 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008065 break;
8066 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008067 case Instruction::Trunc:
8068 case Instruction::ZExt:
8069 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008070 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008071 // just return the source. There's no need to insert it because it is not
8072 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008073 if (I->getOperand(0)->getType() == Ty)
8074 return I->getOperand(0);
8075
Chris Lattner8114b712008-06-18 04:00:49 +00008076 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008077 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008078 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008079 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008080 case Instruction::Select: {
8081 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8082 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8083 Res = SelectInst::Create(I->getOperand(0), True, False);
8084 break;
8085 }
Chris Lattner8114b712008-06-18 04:00:49 +00008086 case Instruction::PHI: {
8087 PHINode *OPN = cast<PHINode>(I);
8088 PHINode *NPN = PHINode::Create(Ty);
8089 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8090 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8091 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8092 }
8093 Res = NPN;
8094 break;
8095 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008096 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008097 // TODO: Can handle more cases here.
Torok Edwinc25e7582009-07-11 20:10:48 +00008098 LLVM_UNREACHABLE("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008099 break;
8100 }
8101
Chris Lattner8114b712008-06-18 04:00:49 +00008102 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008103 return InsertNewInstBefore(Res, *I);
8104}
8105
Reid Spencer3da59db2006-11-27 01:05:10 +00008106/// @brief Implement the transforms common to all CastInst visitors.
8107Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008108 Value *Src = CI.getOperand(0);
8109
Dan Gohman23d9d272007-05-11 21:10:54 +00008110 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008111 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008112 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008113 if (Instruction::CastOps opc =
8114 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8115 // The first cast (CSrc) is eliminable so we need to fix up or replace
8116 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008117 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008118 }
8119 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008120
Reid Spencer3da59db2006-11-27 01:05:10 +00008121 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008122 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8123 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8124 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008125
8126 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008127 if (isa<PHINode>(Src))
8128 if (Instruction *NV = FoldOpIntoPhi(CI))
8129 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008130
Reid Spencer3da59db2006-11-27 01:05:10 +00008131 return 0;
8132}
8133
Chris Lattner46cd5a12009-01-09 05:44:56 +00008134/// FindElementAtOffset - Given a type and a constant offset, determine whether
8135/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008136/// the specified offset. If so, fill them into NewIndices and return the
8137/// resultant element type, otherwise return null.
8138static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8139 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008140 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008141 LLVMContext *Context) {
Chris Lattner3914f722009-01-24 01:00:13 +00008142 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008143
8144 // Start with the index over the outer type. Note that the type size
8145 // might be zero (even if the offset isn't zero) if the indexed type
8146 // is something like [0 x {int, int}]
8147 const Type *IntPtrTy = TD->getIntPtrType();
8148 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008149 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008150 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008151 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008152
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008153 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008154 if (Offset < 0) {
8155 --FirstIdx;
8156 Offset += TySize;
8157 assert(Offset >= 0);
8158 }
8159 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8160 }
8161
Owen Andersond672ecb2009-07-03 00:17:18 +00008162 NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008163
8164 // Index into the types. If we fail, set OrigBase to null.
8165 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008166 // Indexing into tail padding between struct/array elements.
8167 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008168 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008169
Chris Lattner46cd5a12009-01-09 05:44:56 +00008170 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8171 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008172 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8173 "Offset must stay within the indexed type");
8174
Chris Lattner46cd5a12009-01-09 05:44:56 +00008175 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Andersond672ecb2009-07-03 00:17:18 +00008176 NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008177
8178 Offset -= SL->getElementOffset(Elt);
8179 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008180 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008181 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008182 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersond672ecb2009-07-03 00:17:18 +00008183 NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008184 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008185 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008186 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008187 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008188 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008189 }
8190 }
8191
Chris Lattner3914f722009-01-24 01:00:13 +00008192 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008193}
8194
Chris Lattnerd3e28342007-04-27 17:44:50 +00008195/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8196Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8197 Value *Src = CI.getOperand(0);
8198
Chris Lattnerd3e28342007-04-27 17:44:50 +00008199 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008200 // If casting the result of a getelementptr instruction with no offset, turn
8201 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008202 if (GEP->hasAllZeroIndices()) {
8203 // Changing the cast operand is usually not a good idea but it is safe
8204 // here because the pointer operand is being replaced with another
8205 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00008206 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008207 CI.setOperand(0, GEP->getOperand(0));
8208 return &CI;
8209 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008210
8211 // If the GEP has a single use, and the base pointer is a bitcast, and the
8212 // GEP computes a constant offset, see if we can convert these three
8213 // instructions into fewer. This typically happens with unions and other
8214 // non-type-safe code.
8215 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8216 if (GEP->hasAllConstantIndices()) {
8217 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008218 ConstantInt *OffsetV =
8219 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008220 int64_t Offset = OffsetV->getSExtValue();
8221
8222 // Get the base pointer input of the bitcast, and the type it points to.
8223 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8224 const Type *GEPIdxTy =
8225 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008226 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008227 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008228 // If we were able to index down into an element, create the GEP
8229 // and bitcast the result. This eliminates one bitcast, potentially
8230 // two.
8231 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8232 NewIndices.begin(),
8233 NewIndices.end(), "");
8234 InsertNewInstBefore(NGEP, CI);
8235 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008236
Chris Lattner46cd5a12009-01-09 05:44:56 +00008237 if (isa<BitCastInst>(CI))
8238 return new BitCastInst(NGEP, CI.getType());
8239 assert(isa<PtrToIntInst>(CI));
8240 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008241 }
8242 }
8243 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008244 }
8245
8246 return commonCastTransforms(CI);
8247}
8248
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008249/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8250/// type like i42. We don't want to introduce operations on random non-legal
8251/// integer types where they don't already exist in the code. In the future,
8252/// we should consider making this based off target-data, so that 32-bit targets
8253/// won't get i64 operations etc.
8254static bool isSafeIntegerType(const Type *Ty) {
8255 switch (Ty->getPrimitiveSizeInBits()) {
8256 case 8:
8257 case 16:
8258 case 32:
8259 case 64:
8260 return true;
8261 default:
8262 return false;
8263 }
8264}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008265
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008266/// commonIntCastTransforms - This function implements the common transforms
8267/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008268Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8269 if (Instruction *Result = commonCastTransforms(CI))
8270 return Result;
8271
8272 Value *Src = CI.getOperand(0);
8273 const Type *SrcTy = Src->getType();
8274 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008275 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8276 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008277
Reid Spencer3da59db2006-11-27 01:05:10 +00008278 // See if we can simplify any instructions used by the LHS whose sole
8279 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008280 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008281 return &CI;
8282
8283 // If the source isn't an instruction or has more than one use then we
8284 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008285 Instruction *SrcI = dyn_cast<Instruction>(Src);
8286 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008287 return 0;
8288
Chris Lattnerc739cd62007-03-03 05:27:34 +00008289 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008290 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008291 // Only do this if the dest type is a simple type, don't convert the
8292 // expression tree to something weird like i93 unless the source is also
8293 // strange.
8294 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008295 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8296 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008297 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008298 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008299 // eliminates the cast, so it is always a win. If this is a zero-extension,
8300 // we need to do an AND to maintain the clear top-part of the computation,
8301 // so we require that the input have eliminated at least one cast. If this
8302 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008303 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008304 bool DoXForm = false;
8305 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008306 switch (CI.getOpcode()) {
8307 default:
8308 // All the others use floating point so we shouldn't actually
8309 // get here because of the check above.
Torok Edwinc25e7582009-07-11 20:10:48 +00008310 LLVM_UNREACHABLE("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008311 case Instruction::Trunc:
8312 DoXForm = true;
8313 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008314 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008315 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008316 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008317 // If it's unnecessary to issue an AND to clear the high bits, it's
8318 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008319 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008320 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8321 if (MaskedValueIsZero(TryRes, Mask))
8322 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008323
8324 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008325 if (TryI->use_empty())
8326 EraseInstFromFunction(*TryI);
8327 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008328 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008329 }
Evan Chengf35fd542009-01-15 17:01:23 +00008330 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008331 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008332 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008333 // If we do not have to emit the truncate + sext pair, then it's always
8334 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008335 //
8336 // It's not safe to eliminate the trunc + sext pair if one of the
8337 // eliminated cast is a truncate. e.g.
8338 // t2 = trunc i32 t1 to i16
8339 // t3 = sext i16 t2 to i32
8340 // !=
8341 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008342 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008343 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8344 if (NumSignBits > (DestBitSize - SrcBitSize))
8345 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008346
8347 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008348 if (TryI->use_empty())
8349 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008350 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008351 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008352 }
Evan Chengf35fd542009-01-15 17:01:23 +00008353 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008354
8355 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008356 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8357 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008358 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8359 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008360 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008361 // Just replace this cast with the result.
8362 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008363
Reid Spencer3da59db2006-11-27 01:05:10 +00008364 assert(Res->getType() == DestTy);
8365 switch (CI.getOpcode()) {
Torok Edwinc25e7582009-07-11 20:10:48 +00008366 default: LLVM_UNREACHABLE("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008367 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008368 // Just replace this cast with the result.
8369 return ReplaceInstUsesWith(CI, Res);
8370 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008371 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008372
8373 // If the high bits are already zero, just replace this cast with the
8374 // result.
8375 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8376 if (MaskedValueIsZero(Res, Mask))
8377 return ReplaceInstUsesWith(CI, Res);
8378
8379 // We need to emit an AND to clear the high bits.
Owen Andersond672ecb2009-07-03 00:17:18 +00008380 Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
Chris Lattnercd1d6d52007-04-02 05:48:58 +00008381 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008382 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008383 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008384 case Instruction::SExt: {
8385 // If the high bits are already filled with sign bit, just replace this
8386 // cast with the result.
8387 unsigned NumSignBits = ComputeNumSignBits(Res);
8388 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008389 return ReplaceInstUsesWith(CI, Res);
8390
Reid Spencer3da59db2006-11-27 01:05:10 +00008391 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008392 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008393 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8394 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008395 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008396 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008397 }
8398 }
8399
8400 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8401 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8402
8403 switch (SrcI->getOpcode()) {
8404 case Instruction::Add:
8405 case Instruction::Mul:
8406 case Instruction::And:
8407 case Instruction::Or:
8408 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008409 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008410 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8411 // Don't insert two casts unless at least one can be eliminated.
8412 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008413 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman65445c52009-07-13 21:45:57 +00008414 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8415 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008416 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008417 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008418 }
8419 }
8420
8421 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8422 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8423 SrcI->getOpcode() == Instruction::Xor &&
Owen Andersond672ecb2009-07-03 00:17:18 +00008424 Op1 == Context->getConstantIntTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008425 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008426 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008427 return BinaryOperator::CreateXor(New,
8428 Context->getConstantInt(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008429 }
8430 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008431
Eli Friedman65445c52009-07-13 21:45:57 +00008432 case Instruction::Shl: {
8433 // Canonicalize trunc inside shl, if we can.
8434 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8435 if (CI && DestBitSize < SrcBitSize &&
8436 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8437 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8438 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008439 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008440 }
8441 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008442 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008443 }
8444 return 0;
8445}
8446
Chris Lattner8a9f5712007-04-11 06:57:46 +00008447Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008448 if (Instruction *Result = commonIntCastTransforms(CI))
8449 return Result;
8450
8451 Value *Src = CI.getOperand(0);
8452 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008453 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8454 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008455
8456 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00008457 if (DestBitWidth == 1 &&
8458 isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008459 Constant *One = Context->getConstantInt(Src->getType(), 1);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008460 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008461 Value *Zero = Context->getNullValue(Src->getType());
Owen Anderson333c4002009-07-09 23:48:35 +00008462 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008463 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008464
Chris Lattner4f9797d2009-03-24 18:15:30 +00008465 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8466 ConstantInt *ShAmtV = 0;
8467 Value *ShiftOp = 0;
8468 if (Src->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008469 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008470 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8471
8472 // Get a mask for the bits shifting in.
8473 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8474 if (MaskedValueIsZero(ShiftOp, Mask)) {
8475 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersond672ecb2009-07-03 00:17:18 +00008476 return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008477
8478 // Okay, we can shrink this. Truncate the input, then return a new
8479 // shift.
8480 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008481 Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008482 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008483 }
8484 }
8485
8486 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008487}
8488
Evan Chengb98a10e2008-03-24 00:21:34 +00008489/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8490/// in order to eliminate the icmp.
8491Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8492 bool DoXform) {
8493 // If we are just checking for a icmp eq of a single bit and zext'ing it
8494 // to an integer, then shift the bit to the appropriate place and then
8495 // cast to integer to avoid the comparison.
8496 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8497 const APInt &Op1CV = Op1C->getValue();
8498
8499 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8500 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8501 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8502 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8503 if (!DoXform) return ICI;
8504
8505 Value *In = ICI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00008506 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008507 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008508 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008509 In->getName()+".lobit"),
8510 CI);
8511 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008512 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008513 false/*ZExt*/, "tmp", &CI);
8514
8515 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008516 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008517 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008518 In->getName()+".not"),
8519 CI);
8520 }
8521
8522 return ReplaceInstUsesWith(CI, In);
8523 }
8524
8525
8526
8527 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8528 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8529 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8530 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8531 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8532 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8533 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8534 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8535 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8536 // This only works for EQ and NE
8537 ICI->isEquality()) {
8538 // If Op1C some other power of two, convert:
8539 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8540 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8541 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8542 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8543
8544 APInt KnownZeroMask(~KnownZero);
8545 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8546 if (!DoXform) return ICI;
8547
8548 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8549 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8550 // (X&4) == 2 --> false
8551 // (X&4) != 2 --> true
Owen Andersond672ecb2009-07-03 00:17:18 +00008552 Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8553 Res = Context->getConstantExprZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008554 return ReplaceInstUsesWith(CI, Res);
8555 }
8556
8557 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8558 Value *In = ICI->getOperand(0);
8559 if (ShiftAmt) {
8560 // Perform a logical shr by shiftamt.
8561 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008562 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersond672ecb2009-07-03 00:17:18 +00008563 Context->getConstantInt(In->getType(), ShiftAmt),
Evan Chengb98a10e2008-03-24 00:21:34 +00008564 In->getName()+".lobit"), CI);
8565 }
8566
8567 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersond672ecb2009-07-03 00:17:18 +00008568 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008569 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008570 InsertNewInstBefore(cast<Instruction>(In), CI);
8571 }
8572
8573 if (CI.getType() == In->getType())
8574 return ReplaceInstUsesWith(CI, In);
8575 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008576 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008577 }
8578 }
8579 }
8580
8581 return 0;
8582}
8583
Chris Lattner8a9f5712007-04-11 06:57:46 +00008584Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008585 // If one of the common conversion will work ..
8586 if (Instruction *Result = commonIntCastTransforms(CI))
8587 return Result;
8588
8589 Value *Src = CI.getOperand(0);
8590
Chris Lattnera84f47c2009-02-17 20:47:23 +00008591 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8592 // types and if the sizes are just right we can convert this into a logical
8593 // 'and' which will be much cheaper than the pair of casts.
8594 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8595 // Get the sizes of the types involved. We know that the intermediate type
8596 // will be smaller than A or C, but don't know the relation between A and C.
8597 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008598 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8599 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8600 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008601 // If we're actually extending zero bits, then if
8602 // SrcSize < DstSize: zext(a & mask)
8603 // SrcSize == DstSize: a & mask
8604 // SrcSize > DstSize: trunc(a) & mask
8605 if (SrcSize < DstSize) {
8606 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008607 Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008608 Instruction *And =
8609 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8610 InsertNewInstBefore(And, CI);
8611 return new ZExtInst(And, CI.getType());
8612 } else if (SrcSize == DstSize) {
8613 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008614 return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008615 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008616 } else if (SrcSize > DstSize) {
8617 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8618 InsertNewInstBefore(Trunc, CI);
8619 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008620 return BinaryOperator::CreateAnd(Trunc,
8621 Context->getConstantInt(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008622 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008623 }
8624 }
8625
Evan Chengb98a10e2008-03-24 00:21:34 +00008626 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8627 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008628
Evan Chengb98a10e2008-03-24 00:21:34 +00008629 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8630 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8631 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8632 // of the (zext icmp) will be transformed.
8633 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8634 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8635 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8636 (transformZExtICmp(LHS, CI, false) ||
8637 transformZExtICmp(RHS, CI, false))) {
8638 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8639 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008640 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008641 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008642 }
8643
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008644 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008645 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8646 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8647 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8648 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008649 if (TI0->getType() == CI.getType())
8650 return
8651 BinaryOperator::CreateAnd(TI0,
Owen Andersond672ecb2009-07-03 00:17:18 +00008652 Context->getConstantExprZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008653 }
8654
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008655 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8656 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8657 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8658 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8659 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8660 And->getOperand(1) == C)
8661 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8662 Value *TI0 = TI->getOperand(0);
8663 if (TI0->getType() == CI.getType()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008664 Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008665 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8666 InsertNewInstBefore(NewAnd, *And);
8667 return BinaryOperator::CreateXor(NewAnd, ZC);
8668 }
8669 }
8670
Reid Spencer3da59db2006-11-27 01:05:10 +00008671 return 0;
8672}
8673
Chris Lattner8a9f5712007-04-11 06:57:46 +00008674Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008675 if (Instruction *I = commonIntCastTransforms(CI))
8676 return I;
8677
Chris Lattner8a9f5712007-04-11 06:57:46 +00008678 Value *Src = CI.getOperand(0);
8679
Dan Gohman1975d032008-10-30 20:40:10 +00008680 // Canonicalize sign-extend from i1 to a select.
8681 if (Src->getType() == Type::Int1Ty)
8682 return SelectInst::Create(Src,
Owen Anderson73c6b712009-07-13 20:58:05 +00008683 Context->getAllOnesValue(CI.getType()),
Owen Andersond672ecb2009-07-03 00:17:18 +00008684 Context->getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008685
8686 // See if the value being truncated is already sign extended. If so, just
8687 // eliminate the trunc/sext pair.
8688 if (getOpcode(Src) == Instruction::Trunc) {
8689 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008690 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8691 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8692 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008693 unsigned NumSignBits = ComputeNumSignBits(Op);
8694
8695 if (OpBits == DestBits) {
8696 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8697 // bits, it is already ready.
8698 if (NumSignBits > DestBits-MidBits)
8699 return ReplaceInstUsesWith(CI, Op);
8700 } else if (OpBits < DestBits) {
8701 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8702 // bits, just sext from i32.
8703 if (NumSignBits > OpBits-MidBits)
8704 return new SExtInst(Op, CI.getType(), "tmp");
8705 } else {
8706 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8707 // bits, just truncate to i32.
8708 if (NumSignBits > OpBits-MidBits)
8709 return new TruncInst(Op, CI.getType(), "tmp");
8710 }
8711 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008712
8713 // If the input is a shl/ashr pair of a same constant, then this is a sign
8714 // extension from a smaller value. If we could trust arbitrary bitwidth
8715 // integers, we could turn this into a truncate to the smaller bit and then
8716 // use a sext for the whole extension. Since we don't, look deeper and check
8717 // for a truncate. If the source and dest are the same type, eliminate the
8718 // trunc and extend and just do shifts. For example, turn:
8719 // %a = trunc i32 %i to i8
8720 // %b = shl i8 %a, 6
8721 // %c = ashr i8 %b, 6
8722 // %d = sext i8 %c to i32
8723 // into:
8724 // %a = shl i32 %i, 30
8725 // %d = ashr i32 %a, 30
8726 Value *A = 0;
8727 ConstantInt *BA = 0, *CA = 0;
8728 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008729 m_ConstantInt(CA)), *Context) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008730 BA == CA && isa<TruncInst>(A)) {
8731 Value *I = cast<TruncInst>(A)->getOperand(0);
8732 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008733 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8734 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008735 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersond672ecb2009-07-03 00:17:18 +00008736 Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
Chris Lattner46bbad22008-08-06 07:35:52 +00008737 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8738 CI.getName()), CI);
8739 return BinaryOperator::CreateAShr(I, ShAmtV);
8740 }
8741 }
8742
Chris Lattnerba417832007-04-11 06:12:58 +00008743 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008744}
8745
Chris Lattnerb7530652008-01-27 05:29:54 +00008746/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8747/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008748static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008749 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008750 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008751 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008752 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8753 if (!losesInfo)
Owen Andersond672ecb2009-07-03 00:17:18 +00008754 return Context->getConstantFP(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008755 return 0;
8756}
8757
8758/// LookThroughFPExtensions - If this is an fp extension instruction, look
8759/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008760static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008761 if (Instruction *I = dyn_cast<Instruction>(V))
8762 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008763 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008764
8765 // If this value is a constant, return the constant in the smallest FP type
8766 // that can accurately represent it. This allows us to turn
8767 // (float)((double)X+2.0) into x+2.0f.
8768 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8769 if (CFP->getType() == Type::PPC_FP128Ty)
8770 return V; // No constant folding of this.
8771 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008772 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008773 return V;
8774 if (CFP->getType() == Type::DoubleTy)
8775 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008776 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008777 return V;
8778 // Don't try to shrink to various long double types.
8779 }
8780
8781 return V;
8782}
8783
8784Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8785 if (Instruction *I = commonCastTransforms(CI))
8786 return I;
8787
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008788 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008789 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008790 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008791 // many builtins (sqrt, etc).
8792 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8793 if (OpI && OpI->hasOneUse()) {
8794 switch (OpI->getOpcode()) {
8795 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008796 case Instruction::FAdd:
8797 case Instruction::FSub:
8798 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008799 case Instruction::FDiv:
8800 case Instruction::FRem:
8801 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008802 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8803 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008804 if (LHSTrunc->getType() != SrcTy &&
8805 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008806 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008807 // If the source types were both smaller than the destination type of
8808 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008809 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8810 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008811 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8812 CI.getType(), CI);
8813 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8814 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008815 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008816 }
8817 }
8818 break;
8819 }
8820 }
8821 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008822}
8823
8824Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8825 return commonCastTransforms(CI);
8826}
8827
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008828Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008829 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8830 if (OpI == 0)
8831 return commonCastTransforms(FI);
8832
8833 // fptoui(uitofp(X)) --> X
8834 // fptoui(sitofp(X)) --> X
8835 // This is safe if the intermediate type has enough bits in its mantissa to
8836 // accurately represent all values of X. For example, do not do this with
8837 // i64->float->i64. This is also safe for sitofp case, because any negative
8838 // 'X' value would cause an undefined result for the fptoui.
8839 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8840 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008841 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008842 OpI->getType()->getFPMantissaWidth())
8843 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008844
8845 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008846}
8847
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008848Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008849 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8850 if (OpI == 0)
8851 return commonCastTransforms(FI);
8852
8853 // fptosi(sitofp(X)) --> X
8854 // fptosi(uitofp(X)) --> X
8855 // This is safe if the intermediate type has enough bits in its mantissa to
8856 // accurately represent all values of X. For example, do not do this with
8857 // i64->float->i64. This is also safe for sitofp case, because any negative
8858 // 'X' value would cause an undefined result for the fptoui.
8859 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8860 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008861 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008862 OpI->getType()->getFPMantissaWidth())
8863 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008864
8865 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008866}
8867
8868Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8869 return commonCastTransforms(CI);
8870}
8871
8872Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8873 return commonCastTransforms(CI);
8874}
8875
Chris Lattnera0e69692009-03-24 18:35:40 +00008876Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8877 // If the destination integer type is smaller than the intptr_t type for
8878 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8879 // trunc to be exposed to other transforms. Don't do this for extending
8880 // ptrtoint's, because we don't know if the target sign or zero extends its
8881 // pointers.
Dan Gohman6de29f82009-06-15 22:12:54 +00008882 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008883 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8884 TD->getIntPtrType(),
8885 "tmp"), CI);
8886 return new TruncInst(P, CI.getType());
8887 }
8888
Chris Lattnerd3e28342007-04-27 17:44:50 +00008889 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008890}
8891
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008892Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008893 // If the source integer type is larger than the intptr_t type for
8894 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8895 // allows the trunc to be exposed to other transforms. Don't do this for
8896 // extending inttoptr's, because we don't know if the target sign or zero
8897 // extends to pointers.
Dan Gohman6de29f82009-06-15 22:12:54 +00008898 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008899 TD->getPointerSizeInBits()) {
8900 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8901 TD->getIntPtrType(),
8902 "tmp"), CI);
8903 return new IntToPtrInst(P, CI.getType());
8904 }
8905
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008906 if (Instruction *I = commonCastTransforms(CI))
8907 return I;
8908
8909 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8910 if (!DestPointee->isSized()) return 0;
8911
8912 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8913 ConstantInt *Cst;
8914 Value *X;
8915 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008916 m_ConstantInt(Cst)), *Context)) {
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008917 // If the source and destination operands have the same type, see if this
8918 // is a single-index GEP.
8919 if (X->getType() == CI.getType()) {
8920 // Get the size of the pointee type.
Duncan Sands777d2302009-05-09 07:06:46 +00008921 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008922
8923 // Convert the constant to intptr type.
8924 APInt Offset = Cst->getValue();
8925 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8926
8927 // If Offset is evenly divisible by Size, we can do this xform.
8928 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8929 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Owen Andersond672ecb2009-07-03 00:17:18 +00008930 return GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008931 }
8932 }
8933 // TODO: Could handle other cases, e.g. where add is indexing into field of
8934 // struct etc.
8935 } else if (CI.getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008936 match(CI.getOperand(0), m_Add(m_Value(X),
8937 m_ConstantInt(Cst)), *Context)) {
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008938 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8939 // "inttoptr+GEP" instead of "add+intptr".
8940
8941 // Get the size of the pointee type.
Duncan Sands777d2302009-05-09 07:06:46 +00008942 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008943
8944 // Convert the constant to intptr type.
8945 APInt Offset = Cst->getValue();
8946 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8947
8948 // If Offset is evenly divisible by Size, we can do this xform.
8949 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8950 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8951
8952 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8953 "tmp"), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008954 return GetElementPtrInst::Create(P,
8955 Context->getConstantInt(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008956 }
8957 }
8958 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008959}
8960
Chris Lattnerd3e28342007-04-27 17:44:50 +00008961Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008962 // If the operands are integer typed then apply the integer transforms,
8963 // otherwise just apply the common ones.
8964 Value *Src = CI.getOperand(0);
8965 const Type *SrcTy = Src->getType();
8966 const Type *DestTy = CI.getType();
8967
Eli Friedman7e25d452009-07-13 20:53:00 +00008968 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008969 if (Instruction *I = commonPointerCastTransforms(CI))
8970 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008971 } else {
8972 if (Instruction *Result = commonCastTransforms(CI))
8973 return Result;
8974 }
8975
8976
8977 // Get rid of casts from one type to the same type. These are useless and can
8978 // be replaced by the operand.
8979 if (DestTy == Src->getType())
8980 return ReplaceInstUsesWith(CI, Src);
8981
Reid Spencer3da59db2006-11-27 01:05:10 +00008982 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008983 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8984 const Type *DstElTy = DstPTy->getElementType();
8985 const Type *SrcElTy = SrcPTy->getElementType();
8986
Nate Begeman83ad90a2008-03-31 00:22:16 +00008987 // If the address spaces don't match, don't eliminate the bitcast, which is
8988 // required for changing types.
8989 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8990 return 0;
8991
Chris Lattnerd3e28342007-04-27 17:44:50 +00008992 // If we are casting a malloc or alloca to a pointer to a type of the same
8993 // size, rewrite the allocation instruction to allocate the "right" type.
8994 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8995 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8996 return V;
8997
Chris Lattnerd717c182007-05-05 22:32:24 +00008998 // If the source and destination are pointers, and this cast is equivalent
8999 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00009000 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Andersond672ecb2009-07-03 00:17:18 +00009001 Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
Chris Lattnerd3e28342007-04-27 17:44:50 +00009002 unsigned NumZeros = 0;
9003 while (SrcElTy != DstElTy &&
9004 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9005 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9006 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9007 ++NumZeros;
9008 }
Chris Lattner4e998b22004-09-29 05:07:12 +00009009
Chris Lattnerd3e28342007-04-27 17:44:50 +00009010 // If we found a path from the src to dest, create the getelementptr now.
9011 if (SrcElTy == DstElTy) {
9012 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00009013 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
9014 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00009015 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009016 }
Chris Lattner24c8e382003-07-24 17:35:25 +00009017
Reid Spencer3da59db2006-11-27 01:05:10 +00009018 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9019 if (SVI->hasOneUse()) {
9020 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9021 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009022 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009023 cast<VectorType>(DestTy)->getNumElements() ==
9024 SVI->getType()->getNumElements() &&
9025 SVI->getType()->getNumElements() ==
9026 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009027 CastInst *Tmp;
9028 // If either of the operands is a cast from CI.getType(), then
9029 // evaluating the shuffle in the casted destination's type will allow
9030 // us to eliminate at least one cast.
9031 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9032 Tmp->getOperand(0)->getType() == DestTy) ||
9033 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9034 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009035 Value *LHS = InsertCastBefore(Instruction::BitCast,
9036 SVI->getOperand(0), DestTy, CI);
9037 Value *RHS = InsertCastBefore(Instruction::BitCast,
9038 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009039 // Return a new shuffle vector. Use the same element ID's, as we
9040 // know the vector types match #elts.
9041 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009042 }
9043 }
9044 }
9045 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009046 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009047}
9048
Chris Lattnere576b912004-04-09 23:46:01 +00009049/// GetSelectFoldableOperands - We want to turn code that looks like this:
9050/// %C = or %A, %B
9051/// %D = select %cond, %C, %A
9052/// into:
9053/// %C = select %cond, %B, 0
9054/// %D = or %A, %C
9055///
9056/// Assuming that the specified instruction is an operand to the select, return
9057/// a bitmask indicating which operands of this instruction are foldable if they
9058/// equal the other incoming value of the select.
9059///
9060static unsigned GetSelectFoldableOperands(Instruction *I) {
9061 switch (I->getOpcode()) {
9062 case Instruction::Add:
9063 case Instruction::Mul:
9064 case Instruction::And:
9065 case Instruction::Or:
9066 case Instruction::Xor:
9067 return 3; // Can fold through either operand.
9068 case Instruction::Sub: // Can only fold on the amount subtracted.
9069 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009070 case Instruction::LShr:
9071 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009072 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009073 default:
9074 return 0; // Cannot fold
9075 }
9076}
9077
9078/// GetSelectFoldableConstant - For the same transformation as the previous
9079/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009080static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009081 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009082 switch (I->getOpcode()) {
Torok Edwin7d696d82009-07-11 13:10:19 +00009083 default: LLVM_UNREACHABLE("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009084 case Instruction::Add:
9085 case Instruction::Sub:
9086 case Instruction::Or:
9087 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009088 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009089 case Instruction::LShr:
9090 case Instruction::AShr:
Owen Andersond672ecb2009-07-03 00:17:18 +00009091 return Context->getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009092 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00009093 return Context->getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009094 case Instruction::Mul:
Owen Andersond672ecb2009-07-03 00:17:18 +00009095 return Context->getConstantInt(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009096 }
9097}
9098
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009099/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9100/// have the same opcode and only one use each. Try to simplify this.
9101Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9102 Instruction *FI) {
9103 if (TI->getNumOperands() == 1) {
9104 // If this is a non-volatile load or a cast from the same type,
9105 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009106 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009107 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9108 return 0;
9109 } else {
9110 return 0; // unknown unary op.
9111 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009112
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009113 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009114 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9115 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009116 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009117 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009118 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009119 }
9120
Reid Spencer832254e2007-02-02 02:16:23 +00009121 // Only handle binary operators here.
9122 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009123 return 0;
9124
9125 // Figure out if the operations have any operands in common.
9126 Value *MatchOp, *OtherOpT, *OtherOpF;
9127 bool MatchIsOpZero;
9128 if (TI->getOperand(0) == FI->getOperand(0)) {
9129 MatchOp = TI->getOperand(0);
9130 OtherOpT = TI->getOperand(1);
9131 OtherOpF = FI->getOperand(1);
9132 MatchIsOpZero = true;
9133 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9134 MatchOp = TI->getOperand(1);
9135 OtherOpT = TI->getOperand(0);
9136 OtherOpF = FI->getOperand(0);
9137 MatchIsOpZero = false;
9138 } else if (!TI->isCommutative()) {
9139 return 0;
9140 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9141 MatchOp = TI->getOperand(0);
9142 OtherOpT = TI->getOperand(1);
9143 OtherOpF = FI->getOperand(0);
9144 MatchIsOpZero = true;
9145 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9146 MatchOp = TI->getOperand(1);
9147 OtherOpT = TI->getOperand(0);
9148 OtherOpF = FI->getOperand(1);
9149 MatchIsOpZero = true;
9150 } else {
9151 return 0;
9152 }
9153
9154 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009155 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9156 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009157 InsertNewInstBefore(NewSI, SI);
9158
9159 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9160 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009161 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009162 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009163 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009164 }
Torok Edwinc25e7582009-07-11 20:10:48 +00009165 LLVM_UNREACHABLE("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009166 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009167}
9168
Evan Chengde621922009-03-31 20:42:45 +00009169static bool isSelect01(Constant *C1, Constant *C2) {
9170 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9171 if (!C1I)
9172 return false;
9173 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9174 if (!C2I)
9175 return false;
9176 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9177}
9178
9179/// FoldSelectIntoOp - Try fold the select into one of the operands to
9180/// facilitate further optimization.
9181Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9182 Value *FalseVal) {
9183 // See the comment above GetSelectFoldableOperands for a description of the
9184 // transformation we are doing here.
9185 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9186 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9187 !isa<Constant>(FalseVal)) {
9188 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9189 unsigned OpToFold = 0;
9190 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9191 OpToFold = 1;
9192 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9193 OpToFold = 2;
9194 }
9195
9196 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009197 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009198 Value *OOp = TVI->getOperand(2-OpToFold);
9199 // Avoid creating select between 2 constants unless it's selecting
9200 // between 0 and 1.
9201 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9202 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9203 InsertNewInstBefore(NewSel, SI);
9204 NewSel->takeName(TVI);
9205 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9206 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc25e7582009-07-11 20:10:48 +00009207 LLVM_UNREACHABLE("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009208 }
9209 }
9210 }
9211 }
9212 }
9213
9214 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9215 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9216 !isa<Constant>(TrueVal)) {
9217 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9218 unsigned OpToFold = 0;
9219 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9220 OpToFold = 1;
9221 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9222 OpToFold = 2;
9223 }
9224
9225 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009226 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009227 Value *OOp = FVI->getOperand(2-OpToFold);
9228 // Avoid creating select between 2 constants unless it's selecting
9229 // between 0 and 1.
9230 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9231 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9232 InsertNewInstBefore(NewSel, SI);
9233 NewSel->takeName(FVI);
9234 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9235 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc25e7582009-07-11 20:10:48 +00009236 LLVM_UNREACHABLE("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009237 }
9238 }
9239 }
9240 }
9241 }
9242
9243 return 0;
9244}
9245
Dan Gohman81b28ce2008-09-16 18:46:06 +00009246/// visitSelectInstWithICmp - Visit a SelectInst that has an
9247/// ICmpInst as its first operand.
9248///
9249Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9250 ICmpInst *ICI) {
9251 bool Changed = false;
9252 ICmpInst::Predicate Pred = ICI->getPredicate();
9253 Value *CmpLHS = ICI->getOperand(0);
9254 Value *CmpRHS = ICI->getOperand(1);
9255 Value *TrueVal = SI.getTrueValue();
9256 Value *FalseVal = SI.getFalseValue();
9257
9258 // Check cases where the comparison is with a constant that
9259 // can be adjusted to fit the min/max idiom. We may edit ICI in
9260 // place here, so make sure the select is the only user.
9261 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009262 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009263 switch (Pred) {
9264 default: break;
9265 case ICmpInst::ICMP_ULT:
9266 case ICmpInst::ICMP_SLT: {
9267 // X < MIN ? T : F --> F
9268 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9269 return ReplaceInstUsesWith(SI, FalseVal);
9270 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009271 Constant *AdjustedRHS = SubOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009272 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9273 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9274 Pred = ICmpInst::getSwappedPredicate(Pred);
9275 CmpRHS = AdjustedRHS;
9276 std::swap(FalseVal, TrueVal);
9277 ICI->setPredicate(Pred);
9278 ICI->setOperand(1, CmpRHS);
9279 SI.setOperand(1, TrueVal);
9280 SI.setOperand(2, FalseVal);
9281 Changed = true;
9282 }
9283 break;
9284 }
9285 case ICmpInst::ICMP_UGT:
9286 case ICmpInst::ICMP_SGT: {
9287 // X > MAX ? T : F --> F
9288 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9289 return ReplaceInstUsesWith(SI, FalseVal);
9290 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009291 Constant *AdjustedRHS = AddOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009292 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9293 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9294 Pred = ICmpInst::getSwappedPredicate(Pred);
9295 CmpRHS = AdjustedRHS;
9296 std::swap(FalseVal, TrueVal);
9297 ICI->setPredicate(Pred);
9298 ICI->setOperand(1, CmpRHS);
9299 SI.setOperand(1, TrueVal);
9300 SI.setOperand(2, FalseVal);
9301 Changed = true;
9302 }
9303 break;
9304 }
9305 }
9306
Dan Gohman1975d032008-10-30 20:40:10 +00009307 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9308 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009309 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009310 if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9311 match(FalseVal, m_ConstantInt<0>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009312 Pred = ICI->getPredicate();
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009313 else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9314 match(FalseVal, m_ConstantInt<-1>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009315 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9316
Dan Gohman1975d032008-10-30 20:40:10 +00009317 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9318 // If we are just checking for a icmp eq of a single bit and zext'ing it
9319 // to an integer, then shift the bit to the appropriate place and then
9320 // cast to integer to avoid the comparison.
9321 const APInt &Op1CV = CI->getValue();
9322
9323 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9324 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9325 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009326 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009327 Value *In = ICI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00009328 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009329 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009330 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9331 In->getName()+".lobit"),
9332 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009333 if (In->getType() != SI.getType())
9334 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009335 true/*SExt*/, "tmp", ICI);
9336
9337 if (Pred == ICmpInst::ICMP_SGT)
Owen Anderson73c6b712009-07-13 20:58:05 +00009338 In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
Dan Gohman1975d032008-10-30 20:40:10 +00009339 In->getName()+".not"), *ICI);
9340
9341 return ReplaceInstUsesWith(SI, In);
9342 }
9343 }
9344 }
9345
Dan Gohman81b28ce2008-09-16 18:46:06 +00009346 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9347 // Transform (X == Y) ? X : Y -> Y
9348 if (Pred == ICmpInst::ICMP_EQ)
9349 return ReplaceInstUsesWith(SI, FalseVal);
9350 // Transform (X != Y) ? X : Y -> X
9351 if (Pred == ICmpInst::ICMP_NE)
9352 return ReplaceInstUsesWith(SI, TrueVal);
9353 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9354
9355 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9356 // Transform (X == Y) ? Y : X -> X
9357 if (Pred == ICmpInst::ICMP_EQ)
9358 return ReplaceInstUsesWith(SI, FalseVal);
9359 // Transform (X != Y) ? Y : X -> Y
9360 if (Pred == ICmpInst::ICMP_NE)
9361 return ReplaceInstUsesWith(SI, TrueVal);
9362 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9363 }
9364
9365 /// NOTE: if we wanted to, this is where to detect integer ABS
9366
9367 return Changed ? &SI : 0;
9368}
9369
Chris Lattner3d69f462004-03-12 05:52:32 +00009370Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009371 Value *CondVal = SI.getCondition();
9372 Value *TrueVal = SI.getTrueValue();
9373 Value *FalseVal = SI.getFalseValue();
9374
9375 // select true, X, Y -> X
9376 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009377 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009378 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009379
9380 // select C, X, X -> X
9381 if (TrueVal == FalseVal)
9382 return ReplaceInstUsesWith(SI, TrueVal);
9383
Chris Lattnere87597f2004-10-16 18:11:37 +00009384 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9385 return ReplaceInstUsesWith(SI, FalseVal);
9386 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9387 return ReplaceInstUsesWith(SI, TrueVal);
9388 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9389 if (isa<Constant>(TrueVal))
9390 return ReplaceInstUsesWith(SI, TrueVal);
9391 else
9392 return ReplaceInstUsesWith(SI, FalseVal);
9393 }
9394
Reid Spencer4fe16d62007-01-11 18:21:29 +00009395 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009396 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009397 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009398 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009399 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009400 } else {
9401 // Change: A = select B, false, C --> A = and !B, C
9402 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009403 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009404 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009405 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009406 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009407 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009408 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009409 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009410 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009411 } else {
9412 // Change: A = select B, C, true --> A = or !B, C
9413 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009414 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009415 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009416 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009417 }
9418 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009419
9420 // select a, b, a -> a&b
9421 // select a, a, b -> a|b
9422 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009423 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009424 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009425 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009426 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009427
Chris Lattner2eefe512004-04-09 19:05:30 +00009428 // Selecting between two integer constants?
9429 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9430 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009431 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009432 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009433 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009434 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009435 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009436 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009437 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009438 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009439 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009440 }
Chris Lattner457dd822004-06-09 07:59:58 +00009441
Reid Spencere4d87aa2006-12-23 06:05:41 +00009442 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009443 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009444 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009445 // non-constant value, eliminate this whole mess. This corresponds to
9446 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009447 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009448 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009449 cast<Constant>(IC->getOperand(1))->isNullValue())
9450 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9451 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009452 isa<ConstantInt>(ICA->getOperand(1)) &&
9453 (ICA->getOperand(1) == TrueValC ||
9454 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009455 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9456 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009457 // know whether we have a icmp_ne or icmp_eq and whether the
9458 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009459 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009460 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009461 Value *V = ICA;
9462 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009463 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009464 Instruction::Xor, V, ICA->getOperand(1)), SI);
9465 return ReplaceInstUsesWith(SI, V);
9466 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009467 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009468 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009469
9470 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009471 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9472 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009473 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009474 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9475 // This is not safe in general for floating point:
9476 // consider X== -0, Y== +0.
9477 // It becomes safe if either operand is a nonzero constant.
9478 ConstantFP *CFPt, *CFPf;
9479 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9480 !CFPt->getValueAPF().isZero()) ||
9481 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9482 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009483 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009484 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009485 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009486 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009487 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009488 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009489
Reid Spencere4d87aa2006-12-23 06:05:41 +00009490 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009491 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009492 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9493 // This is not safe in general for floating point:
9494 // consider X== -0, Y== +0.
9495 // It becomes safe if either operand is a nonzero constant.
9496 ConstantFP *CFPt, *CFPf;
9497 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9498 !CFPt->getValueAPF().isZero()) ||
9499 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9500 !CFPf->getValueAPF().isZero()))
9501 return ReplaceInstUsesWith(SI, FalseVal);
9502 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009503 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009504 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9505 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009506 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009507 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009508 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009509 }
9510
9511 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009512 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9513 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9514 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009515
Chris Lattner87875da2005-01-13 22:52:24 +00009516 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9517 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9518 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009519 Instruction *AddOp = 0, *SubOp = 0;
9520
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009521 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9522 if (TI->getOpcode() == FI->getOpcode())
9523 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9524 return IV;
9525
9526 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9527 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009528 if ((TI->getOpcode() == Instruction::Sub &&
9529 FI->getOpcode() == Instruction::Add) ||
9530 (TI->getOpcode() == Instruction::FSub &&
9531 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009532 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009533 } else if ((FI->getOpcode() == Instruction::Sub &&
9534 TI->getOpcode() == Instruction::Add) ||
9535 (FI->getOpcode() == Instruction::FSub &&
9536 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009537 AddOp = TI; SubOp = FI;
9538 }
9539
9540 if (AddOp) {
9541 Value *OtherAddOp = 0;
9542 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9543 OtherAddOp = AddOp->getOperand(1);
9544 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9545 OtherAddOp = AddOp->getOperand(0);
9546 }
9547
9548 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009549 // So at this point we know we have (Y -> OtherAddOp):
9550 // select C, (add X, Y), (sub X, Z)
9551 Value *NegVal; // Compute -Z
9552 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009553 NegVal = Context->getConstantExprNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009554 } else {
9555 NegVal = InsertNewInstBefore(
Owen Anderson0a5372e2009-07-13 04:09:18 +00009556 BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9557 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009558 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009559
9560 Value *NewTrueOp = OtherAddOp;
9561 Value *NewFalseOp = NegVal;
9562 if (AddOp != TI)
9563 std::swap(NewTrueOp, NewFalseOp);
9564 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009565 SelectInst::Create(CondVal, NewTrueOp,
9566 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009567
9568 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009569 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009570 }
9571 }
9572 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009573
Chris Lattnere576b912004-04-09 23:46:01 +00009574 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009575 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009576 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9577 if (FoldI)
9578 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009579 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009580
9581 if (BinaryOperator::isNot(CondVal)) {
9582 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9583 SI.setOperand(1, FalseVal);
9584 SI.setOperand(2, TrueVal);
9585 return &SI;
9586 }
9587
Chris Lattner3d69f462004-03-12 05:52:32 +00009588 return 0;
9589}
9590
Dan Gohmaneee962e2008-04-10 18:43:06 +00009591/// EnforceKnownAlignment - If the specified pointer points to an object that
9592/// we control, modify the object's alignment to PrefAlign. This isn't
9593/// often possible though. If alignment is important, a more reliable approach
9594/// is to simply align all global variables and allocation instructions to
9595/// their preferred alignment from the beginning.
9596///
9597static unsigned EnforceKnownAlignment(Value *V,
9598 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009599
Dan Gohmaneee962e2008-04-10 18:43:06 +00009600 User *U = dyn_cast<User>(V);
9601 if (!U) return Align;
9602
9603 switch (getOpcode(U)) {
9604 default: break;
9605 case Instruction::BitCast:
9606 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9607 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009608 // If all indexes are zero, it is just the alignment of the base pointer.
9609 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009610 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009611 if (!isa<Constant>(*i) ||
9612 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009613 AllZeroOperands = false;
9614 break;
9615 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009616
9617 if (AllZeroOperands) {
9618 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009619 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009620 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009621 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009622 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009623 }
9624
9625 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9626 // If there is a large requested alignment and we can, bump up the alignment
9627 // of the global.
9628 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009629 if (GV->getAlignment() >= PrefAlign)
9630 Align = GV->getAlignment();
9631 else {
9632 GV->setAlignment(PrefAlign);
9633 Align = PrefAlign;
9634 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009635 }
9636 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9637 // If there is a requested alignment and if this is an alloca, round up. We
9638 // don't do this for malloc, because some systems can't respect the request.
9639 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009640 if (AI->getAlignment() >= PrefAlign)
9641 Align = AI->getAlignment();
9642 else {
9643 AI->setAlignment(PrefAlign);
9644 Align = PrefAlign;
9645 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009646 }
9647 }
9648
9649 return Align;
9650}
9651
9652/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9653/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9654/// and it is more than the alignment of the ultimate object, see if we can
9655/// increase the alignment of the ultimate object, making this check succeed.
9656unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9657 unsigned PrefAlign) {
9658 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9659 sizeof(PrefAlign) * CHAR_BIT;
9660 APInt Mask = APInt::getAllOnesValue(BitWidth);
9661 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9662 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9663 unsigned TrailZ = KnownZero.countTrailingOnes();
9664 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9665
9666 if (PrefAlign > Align)
9667 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9668
9669 // We don't need to make any adjustment.
9670 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009671}
9672
Chris Lattnerf497b022008-01-13 23:50:23 +00009673Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009674 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009675 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009676 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009677 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009678
9679 if (CopyAlign < MinAlign) {
Owen Andersona547b472009-07-09 18:36:20 +00009680 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9681 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009682 return MI;
9683 }
9684
9685 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9686 // load/store.
9687 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9688 if (MemOpLength == 0) return 0;
9689
Chris Lattner37ac6082008-01-14 00:28:35 +00009690 // Source and destination pointer types are always "i8*" for intrinsic. See
9691 // if the size is something we can handle with a single primitive load/store.
9692 // A single load+store correctly handles overlapping memory in the memmove
9693 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009694 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009695 if (Size == 0) return MI; // Delete this mem transfer.
9696
9697 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009698 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009699
Chris Lattner37ac6082008-01-14 00:28:35 +00009700 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009701 Type *NewPtrTy =
9702 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009703
9704 // Memcpy forces the use of i8* for the source and destination. That means
9705 // that if you're using memcpy to move one double around, you'll get a cast
9706 // from double* to i8*. We'd much rather use a double load+store rather than
9707 // an i64 load+store, here because this improves the odds that the source or
9708 // dest address will be promotable. See if we can find a better type than the
9709 // integer datatype.
9710 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9711 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9712 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9713 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9714 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009715 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009716 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9717 if (STy->getNumElements() == 1)
9718 SrcETy = STy->getElementType(0);
9719 else
9720 break;
9721 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9722 if (ATy->getNumElements() == 1)
9723 SrcETy = ATy->getElementType();
9724 else
9725 break;
9726 } else
9727 break;
9728 }
9729
Dan Gohman8f8e2692008-05-23 01:52:21 +00009730 if (SrcETy->isSingleValueType())
Owen Andersond672ecb2009-07-03 00:17:18 +00009731 NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009732 }
9733 }
9734
9735
Chris Lattnerf497b022008-01-13 23:50:23 +00009736 // If the memcpy/memmove provides better alignment info than we can
9737 // infer, use it.
9738 SrcAlign = std::max(SrcAlign, CopyAlign);
9739 DstAlign = std::max(DstAlign, CopyAlign);
9740
9741 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9742 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009743 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9744 InsertNewInstBefore(L, *MI);
9745 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9746
9747 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009748 MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009749 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009750}
Chris Lattner3d69f462004-03-12 05:52:32 +00009751
Chris Lattner69ea9d22008-04-30 06:39:11 +00009752Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9753 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009754 if (MI->getAlignment() < Alignment) {
Owen Andersona547b472009-07-09 18:36:20 +00009755 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9756 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009757 return MI;
9758 }
9759
9760 // Extract the length and alignment and fill if they are constant.
9761 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9762 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9763 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9764 return 0;
9765 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009766 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009767
9768 // If the length is zero, this is a no-op
9769 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9770
9771 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9772 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009773 const Type *ITy = Context->getIntegerType(Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009774
9775 Value *Dest = MI->getDest();
Owen Andersond672ecb2009-07-03 00:17:18 +00009776 Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009777
9778 // Alignment 0 is identity for alignment 1 for memset, but not store.
9779 if (Alignment == 0) Alignment = 1;
9780
9781 // Extract the fill value and store.
9782 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersond672ecb2009-07-03 00:17:18 +00009783 InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9784 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009785
9786 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009787 MI->setLength(Context->getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009788 return MI;
9789 }
9790
9791 return 0;
9792}
9793
9794
Chris Lattner8b0ea312006-01-13 20:11:04 +00009795/// visitCallInst - CallInst simplification. This mostly only handles folding
9796/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9797/// the heavy lifting.
9798///
Chris Lattner9fe38862003-06-19 17:00:31 +00009799Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009800 // If the caller function is nounwind, mark the call as nounwind, even if the
9801 // callee isn't.
9802 if (CI.getParent()->getParent()->doesNotThrow() &&
9803 !CI.doesNotThrow()) {
9804 CI.setDoesNotThrow();
9805 return &CI;
9806 }
9807
9808
9809
Chris Lattner8b0ea312006-01-13 20:11:04 +00009810 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9811 if (!II) return visitCallSite(&CI);
9812
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009813 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9814 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009815 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009816 bool Changed = false;
9817
9818 // memmove/cpy/set of zero bytes is a noop.
9819 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9820 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9821
Chris Lattner35b9e482004-10-12 04:52:52 +00009822 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009823 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009824 // Replace the instruction with just byte operations. We would
9825 // transform other cases to loads/stores, but we don't know if
9826 // alignment is sufficient.
9827 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009828 }
9829
Chris Lattner35b9e482004-10-12 04:52:52 +00009830 // If we have a memmove and the source operation is a constant global,
9831 // then the source and dest pointers can't alias, so we can change this
9832 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009833 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009834 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9835 if (GVSrc->isConstant()) {
9836 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009837 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9838 const Type *Tys[1];
9839 Tys[0] = CI.getOperand(3)->getType();
9840 CI.setOperand(0,
9841 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009842 Changed = true;
9843 }
Chris Lattnera935db82008-05-28 05:30:41 +00009844
9845 // memmove(x,x,size) -> noop.
9846 if (MMI->getSource() == MMI->getDest())
9847 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009848 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009849
Chris Lattner95a959d2006-03-06 20:18:44 +00009850 // If we can determine a pointer alignment that is bigger than currently
9851 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009852 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009853 if (Instruction *I = SimplifyMemTransfer(MI))
9854 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009855 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9856 if (Instruction *I = SimplifyMemSet(MSI))
9857 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009858 }
9859
Chris Lattner8b0ea312006-01-13 20:11:04 +00009860 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009861 }
9862
9863 switch (II->getIntrinsicID()) {
9864 default: break;
9865 case Intrinsic::bswap:
9866 // bswap(bswap(x)) -> x
9867 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9868 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9869 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9870 break;
9871 case Intrinsic::ppc_altivec_lvx:
9872 case Intrinsic::ppc_altivec_lvxl:
9873 case Intrinsic::x86_sse_loadu_ps:
9874 case Intrinsic::x86_sse2_loadu_pd:
9875 case Intrinsic::x86_sse2_loadu_dq:
9876 // Turn PPC lvx -> load if the pointer is known aligned.
9877 // Turn X86 loadups -> load if the pointer is known aligned.
9878 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9879 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00009880 Context->getPointerTypeUnqual(II->getType()),
Chris Lattner0521e3c2008-06-18 04:33:20 +00009881 CI);
9882 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009883 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009884 break;
9885 case Intrinsic::ppc_altivec_stvx:
9886 case Intrinsic::ppc_altivec_stvxl:
9887 // Turn stvx -> store if the pointer is known aligned.
9888 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9889 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009890 Context->getPointerTypeUnqual(II->getOperand(1)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009891 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9892 return new StoreInst(II->getOperand(1), Ptr);
9893 }
9894 break;
9895 case Intrinsic::x86_sse_storeu_ps:
9896 case Intrinsic::x86_sse2_storeu_pd:
9897 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009898 // Turn X86 storeu -> store if the pointer is known aligned.
9899 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9900 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009901 Context->getPointerTypeUnqual(II->getOperand(2)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009902 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9903 return new StoreInst(II->getOperand(2), Ptr);
9904 }
9905 break;
9906
9907 case Intrinsic::x86_sse_cvttss2si: {
9908 // These intrinsics only demands the 0th element of its input vector. If
9909 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009910 unsigned VWidth =
9911 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9912 APInt DemandedElts(VWidth, 1);
9913 APInt UndefElts(VWidth, 0);
9914 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009915 UndefElts)) {
9916 II->setOperand(1, V);
9917 return II;
9918 }
9919 break;
9920 }
9921
9922 case Intrinsic::ppc_altivec_vperm:
9923 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9924 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9925 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009926
Chris Lattner0521e3c2008-06-18 04:33:20 +00009927 // Check that all of the elements are integer constants or undefs.
9928 bool AllEltsOk = true;
9929 for (unsigned i = 0; i != 16; ++i) {
9930 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9931 !isa<UndefValue>(Mask->getOperand(i))) {
9932 AllEltsOk = false;
9933 break;
9934 }
9935 }
9936
9937 if (AllEltsOk) {
9938 // Cast the input vectors to byte vectors.
9939 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9940 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00009941 Value *Result = Context->getUndef(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009942
Chris Lattner0521e3c2008-06-18 04:33:20 +00009943 // Only extract each element once.
9944 Value *ExtractedElts[32];
9945 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9946
Chris Lattnere2ed0572006-04-06 19:19:17 +00009947 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009948 if (isa<UndefValue>(Mask->getOperand(i)))
9949 continue;
9950 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9951 Idx &= 31; // Match the hardware behavior.
9952
9953 if (ExtractedElts[Idx] == 0) {
9954 Instruction *Elt =
9955 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9956 InsertNewInstBefore(Elt, CI);
9957 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009958 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009959
Chris Lattner0521e3c2008-06-18 04:33:20 +00009960 // Insert this value into the result vector.
9961 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9962 i, "tmp");
9963 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009964 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009965 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009966 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009967 }
9968 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009969
Chris Lattner0521e3c2008-06-18 04:33:20 +00009970 case Intrinsic::stackrestore: {
9971 // If the save is right next to the restore, remove the restore. This can
9972 // happen when variable allocas are DCE'd.
9973 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9974 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9975 BasicBlock::iterator BI = SS;
9976 if (&*++BI == II)
9977 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009978 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009979 }
9980
9981 // Scan down this block to see if there is another stack restore in the
9982 // same block without an intervening call/alloca.
9983 BasicBlock::iterator BI = II;
9984 TerminatorInst *TI = II->getParent()->getTerminator();
9985 bool CannotRemove = false;
9986 for (++BI; &*BI != TI; ++BI) {
9987 if (isa<AllocaInst>(BI)) {
9988 CannotRemove = true;
9989 break;
9990 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009991 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9992 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9993 // If there is a stackrestore below this one, remove this one.
9994 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9995 return EraseInstFromFunction(CI);
9996 // Otherwise, ignore the intrinsic.
9997 } else {
9998 // If we found a non-intrinsic call, we can't remove the stack
9999 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010000 CannotRemove = true;
10001 break;
10002 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010003 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010004 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010005
10006 // If the stack restore is in a return/unwind block and if there are no
10007 // allocas or calls between the restore and the return, nuke the restore.
10008 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10009 return EraseInstFromFunction(CI);
10010 break;
10011 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010012 }
10013
Chris Lattner8b0ea312006-01-13 20:11:04 +000010014 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010015}
10016
10017// InvokeInst simplification
10018//
10019Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010020 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010021}
10022
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010023/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10024/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010025static bool isSafeToEliminateVarargsCast(const CallSite CS,
10026 const CastInst * const CI,
10027 const TargetData * const TD,
10028 const int ix) {
10029 if (!CI->isLosslessCast())
10030 return false;
10031
10032 // The size of ByVal arguments is derived from the type, so we
10033 // can't change to a type with a different size. If the size were
10034 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010035 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010036 return true;
10037
10038 const Type* SrcTy =
10039 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10040 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10041 if (!SrcTy->isSized() || !DstTy->isSized())
10042 return false;
Duncan Sands777d2302009-05-09 07:06:46 +000010043 if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010044 return false;
10045 return true;
10046}
10047
Chris Lattnera44d8a22003-10-07 22:32:43 +000010048// visitCallSite - Improvements for call and invoke instructions.
10049//
10050Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010051 bool Changed = false;
10052
10053 // If the callee is a constexpr cast of a function, attempt to move the cast
10054 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010055 if (transformConstExprCastCall(CS)) return 0;
10056
Chris Lattner6c266db2003-10-07 22:54:13 +000010057 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010058
Chris Lattner08b22ec2005-05-13 07:09:09 +000010059 if (Function *CalleeF = dyn_cast<Function>(Callee))
10060 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10061 Instruction *OldCall = CS.getInstruction();
10062 // If the call and callee calling conventions don't match, this call must
10063 // be unreachable, as the call is undefined.
Owen Andersond672ecb2009-07-03 00:17:18 +000010064 new StoreInst(Context->getConstantIntTrue(),
10065 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10066 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +000010067 if (!OldCall->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000010068 OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010069 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10070 return EraseInstFromFunction(*OldCall);
10071 return 0;
10072 }
10073
Chris Lattner17be6352004-10-18 02:59:09 +000010074 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10075 // This instruction is not reachable, just remove it. We insert a store to
10076 // undef so that we know that this code is not reachable, despite the fact
10077 // that we can't modify the CFG here.
Owen Andersond672ecb2009-07-03 00:17:18 +000010078 new StoreInst(Context->getConstantIntTrue(),
10079 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +000010080 CS.getInstruction());
10081
10082 if (!CS.getInstruction()->use_empty())
10083 CS.getInstruction()->
Owen Andersond672ecb2009-07-03 00:17:18 +000010084 replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010085
10086 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10087 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010088 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Andersond672ecb2009-07-03 00:17:18 +000010089 Context->getConstantIntTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010090 }
Chris Lattner17be6352004-10-18 02:59:09 +000010091 return EraseInstFromFunction(*CS.getInstruction());
10092 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010093
Duncan Sandscdb6d922007-09-17 10:26:40 +000010094 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10095 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10096 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10097 return transformCallThroughTrampoline(CS);
10098
Chris Lattner6c266db2003-10-07 22:54:13 +000010099 const PointerType *PTy = cast<PointerType>(Callee->getType());
10100 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10101 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010102 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010103 // See if we can optimize any arguments passed through the varargs area of
10104 // the call.
10105 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010106 E = CS.arg_end(); I != E; ++I, ++ix) {
10107 CastInst *CI = dyn_cast<CastInst>(*I);
10108 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10109 *I = CI->getOperand(0);
10110 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010111 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010112 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010113 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010114
Duncan Sandsf0c33542007-12-19 21:13:37 +000010115 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010116 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010117 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010118 Changed = true;
10119 }
10120
Chris Lattner6c266db2003-10-07 22:54:13 +000010121 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010122}
10123
Chris Lattner9fe38862003-06-19 17:00:31 +000010124// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10125// attempt to move the cast to the arguments of the call/invoke.
10126//
10127bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10128 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10129 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010130 if (CE->getOpcode() != Instruction::BitCast ||
10131 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010132 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010133 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010134 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010135 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010136
10137 // Okay, this is a cast from a function to a different type. Unless doing so
10138 // would cause a type conversion of one of our arguments, change this call to
10139 // be a direct call with arguments casted to the appropriate types.
10140 //
10141 const FunctionType *FT = Callee->getFunctionType();
10142 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010143 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010144
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010145 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010146 return false; // TODO: Handle multiple return values.
10147
Chris Lattnerf78616b2004-01-14 06:06:08 +000010148 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010149 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010150 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010151 // Conversion is ok if changing from one pointer type to another or from
10152 // a pointer to an integer of the same size.
10153 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +000010154 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +000010155 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010156
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010157 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010158 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010159 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010160 return false; // Cannot transform this return value.
10161
Chris Lattner58d74912008-03-12 17:45:29 +000010162 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010163 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010164 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010165 return false; // Attribute not compatible with transformed value.
10166 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010167
Chris Lattnerf78616b2004-01-14 06:06:08 +000010168 // If the callsite is an invoke instruction, and the return value is used by
10169 // a PHI node in a successor, we cannot change the return type of the call
10170 // because there is no place to put the cast instruction (without breaking
10171 // the critical edge). Bail out in this case.
10172 if (!Caller->use_empty())
10173 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10174 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10175 UI != E; ++UI)
10176 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10177 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010178 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010179 return false;
10180 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010181
10182 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10183 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010184
Chris Lattner9fe38862003-06-19 17:00:31 +000010185 CallSite::arg_iterator AI = CS.arg_begin();
10186 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10187 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010188 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010189
10190 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010191 return false; // Cannot transform this parameter value.
10192
Devang Patel19c87462008-09-26 22:53:05 +000010193 if (CallerPAL.getParamAttributes(i + 1)
10194 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010195 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010196
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010197 // Converting from one pointer type to another or between a pointer and an
10198 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010199 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010200 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10201 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010202 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010203 }
10204
10205 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010206 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010207 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010208
Chris Lattner58d74912008-03-12 17:45:29 +000010209 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10210 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010211 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010212 // won't be dropping them. Check that these extra arguments have attributes
10213 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010214 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10215 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010216 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010217 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010218 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010219 return false;
10220 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010221
Chris Lattner9fe38862003-06-19 17:00:31 +000010222 // Okay, we decided that this is a safe thing to do: go ahead and start
10223 // inserting cast instructions as necessary...
10224 std::vector<Value*> Args;
10225 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010226 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010227 attrVec.reserve(NumCommonArgs);
10228
10229 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010230 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010231
10232 // If the return value is not being used, the type may not be compatible
10233 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010234 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010235
10236 // Add the new return attributes.
10237 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010238 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010239
10240 AI = CS.arg_begin();
10241 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10242 const Type *ParamTy = FT->getParamType(i);
10243 if ((*AI)->getType() == ParamTy) {
10244 Args.push_back(*AI);
10245 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010246 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010247 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010248 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010249 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010250 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010251
10252 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010253 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010254 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010255 }
10256
10257 // If the function takes more arguments than the call was taking, add them
10258 // now...
10259 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000010260 Args.push_back(Context->getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010261
10262 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010263 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010264 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +000010265 cerr << "WARNING: While resolving call to function '"
10266 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010267 } else {
10268 // Add all of the arguments in their promoted form to the arg list...
10269 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10270 const Type *PTy = getPromotedType((*AI)->getType());
10271 if (PTy != (*AI)->getType()) {
10272 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010273 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10274 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010275 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010276 InsertNewInstBefore(Cast, *Caller);
10277 Args.push_back(Cast);
10278 } else {
10279 Args.push_back(*AI);
10280 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010281
Duncan Sandse1e520f2008-01-13 08:02:44 +000010282 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010283 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010284 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010285 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010286 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010287 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010288
Devang Patel19c87462008-09-26 22:53:05 +000010289 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10290 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10291
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010292 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +000010293 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010294
Devang Patel05988662008-09-25 21:00:45 +000010295 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010296
Chris Lattner9fe38862003-06-19 17:00:31 +000010297 Instruction *NC;
10298 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010299 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010300 Args.begin(), Args.end(),
10301 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010302 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010303 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010304 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010305 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10306 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010307 CallInst *CI = cast<CallInst>(Caller);
10308 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010309 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010310 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010311 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010312 }
10313
Chris Lattner6934a042007-02-11 01:23:03 +000010314 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010315 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010316 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010317 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010318 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010319 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010320 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010321
10322 // If this is an invoke instruction, we should insert it after the first
10323 // non-phi, instruction in the normal successor block.
10324 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010325 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010326 InsertNewInstBefore(NC, *I);
10327 } else {
10328 // Otherwise, it's a call, just insert cast right after the call instr
10329 InsertNewInstBefore(NC, *Caller);
10330 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010331 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010332 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000010333 NV = Context->getUndef(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010334 }
10335 }
10336
10337 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10338 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010339 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010340 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010341 return true;
10342}
10343
Duncan Sandscdb6d922007-09-17 10:26:40 +000010344// transformCallThroughTrampoline - Turn a call to a function created by the
10345// init_trampoline intrinsic into a direct call to the underlying function.
10346//
10347Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10348 Value *Callee = CS.getCalledValue();
10349 const PointerType *PTy = cast<PointerType>(Callee->getType());
10350 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010351 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010352
10353 // If the call already has the 'nest' attribute somewhere then give up -
10354 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010355 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010356 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010357
10358 IntrinsicInst *Tramp =
10359 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10360
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010361 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010362 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10363 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10364
Devang Patel05988662008-09-25 21:00:45 +000010365 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010366 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010367 unsigned NestIdx = 1;
10368 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010369 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010370
10371 // Look for a parameter marked with the 'nest' attribute.
10372 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10373 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010374 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010375 // Record the parameter type and any other attributes.
10376 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010377 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010378 break;
10379 }
10380
10381 if (NestTy) {
10382 Instruction *Caller = CS.getInstruction();
10383 std::vector<Value*> NewArgs;
10384 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10385
Devang Patel05988662008-09-25 21:00:45 +000010386 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010387 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010388
Duncan Sandscdb6d922007-09-17 10:26:40 +000010389 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010390 // mean appending it. Likewise for attributes.
10391
Devang Patel19c87462008-09-26 22:53:05 +000010392 // Add any result attributes.
10393 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010394 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010395
Duncan Sandscdb6d922007-09-17 10:26:40 +000010396 {
10397 unsigned Idx = 1;
10398 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10399 do {
10400 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010401 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010402 Value *NestVal = Tramp->getOperand(3);
10403 if (NestVal->getType() != NestTy)
10404 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10405 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010406 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010407 }
10408
10409 if (I == E)
10410 break;
10411
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010412 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010413 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010414 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010415 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010416 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010417
10418 ++Idx, ++I;
10419 } while (1);
10420 }
10421
Devang Patel19c87462008-09-26 22:53:05 +000010422 // Add any function attributes.
10423 if (Attributes Attr = Attrs.getFnAttributes())
10424 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10425
Duncan Sandscdb6d922007-09-17 10:26:40 +000010426 // The trampoline may have been bitcast to a bogus type (FTy).
10427 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010428 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010429
Duncan Sandscdb6d922007-09-17 10:26:40 +000010430 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010431 NewTypes.reserve(FTy->getNumParams()+1);
10432
Duncan Sandscdb6d922007-09-17 10:26:40 +000010433 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010434 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010435 {
10436 unsigned Idx = 1;
10437 FunctionType::param_iterator I = FTy->param_begin(),
10438 E = FTy->param_end();
10439
10440 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010441 if (Idx == NestIdx)
10442 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010443 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010444
10445 if (I == E)
10446 break;
10447
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010448 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010449 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010450
10451 ++Idx, ++I;
10452 } while (1);
10453 }
10454
10455 // Replace the trampoline call with a direct call. Let the generic
10456 // code sort out any function type mismatches.
10457 FunctionType *NewFTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000010458 Context->getFunctionType(FTy->getReturnType(), NewTypes,
10459 FTy->isVarArg());
10460 Constant *NewCallee =
10461 NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10462 NestF : Context->getConstantExprBitCast(NestF,
10463 Context->getPointerTypeUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +000010464 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010465
10466 Instruction *NewCaller;
10467 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010468 NewCaller = InvokeInst::Create(NewCallee,
10469 II->getNormalDest(), II->getUnwindDest(),
10470 NewArgs.begin(), NewArgs.end(),
10471 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010472 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010473 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010474 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010475 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10476 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010477 if (cast<CallInst>(Caller)->isTailCall())
10478 cast<CallInst>(NewCaller)->setTailCall();
10479 cast<CallInst>(NewCaller)->
10480 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010481 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010482 }
10483 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10484 Caller->replaceAllUsesWith(NewCaller);
10485 Caller->eraseFromParent();
10486 RemoveFromWorkList(Caller);
10487 return 0;
10488 }
10489 }
10490
10491 // Replace the trampoline call with a direct call. Since there is no 'nest'
10492 // parameter, there is no need to adjust the argument list. Let the generic
10493 // code sort out any function type mismatches.
10494 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010495 NestF->getType() == PTy ? NestF :
10496 Context->getConstantExprBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010497 CS.setCalledFunction(NewCallee);
10498 return CS.getInstruction();
10499}
10500
Chris Lattner7da52b22006-11-01 04:51:18 +000010501/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10502/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10503/// and a single binop.
10504Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10505 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010506 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010507 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010508 Value *LHSVal = FirstInst->getOperand(0);
10509 Value *RHSVal = FirstInst->getOperand(1);
10510
10511 const Type *LHSType = LHSVal->getType();
10512 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010513
10514 // Scan to see if all operands are the same opcode, all have one use, and all
10515 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010516 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010517 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010518 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010519 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010520 // types or GEP's with different index types.
10521 I->getOperand(0)->getType() != LHSType ||
10522 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010523 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010524
10525 // If they are CmpInst instructions, check their predicates
10526 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10527 if (cast<CmpInst>(I)->getPredicate() !=
10528 cast<CmpInst>(FirstInst)->getPredicate())
10529 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010530
10531 // Keep track of which operand needs a phi node.
10532 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10533 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010534 }
10535
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010536 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010537
Chris Lattner7da52b22006-11-01 04:51:18 +000010538 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010539 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010540 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010541 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010542 NewLHS = PHINode::Create(LHSType,
10543 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010544 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10545 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010546 InsertNewInstBefore(NewLHS, PN);
10547 LHSVal = NewLHS;
10548 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010549
10550 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010551 NewRHS = PHINode::Create(RHSType,
10552 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010553 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10554 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010555 InsertNewInstBefore(NewRHS, PN);
10556 RHSVal = NewRHS;
10557 }
10558
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010559 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010560 if (NewLHS || NewRHS) {
10561 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10562 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10563 if (NewLHS) {
10564 Value *NewInLHS = InInst->getOperand(0);
10565 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10566 }
10567 if (NewRHS) {
10568 Value *NewInRHS = InInst->getOperand(1);
10569 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10570 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010571 }
10572 }
10573
Chris Lattner7da52b22006-11-01 04:51:18 +000010574 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010575 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010576 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Owen Anderson333c4002009-07-09 23:48:35 +000010577 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10578 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010579}
10580
Chris Lattner05f18922008-12-01 02:34:36 +000010581Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10582 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10583
10584 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10585 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010586 // This is true if all GEP bases are allocas and if all indices into them are
10587 // constants.
10588 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010589
10590 // Scan to see if all operands are the same opcode, all have one use, and all
10591 // kill their operands (i.e. the operands have one use).
10592 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10593 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10594 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10595 GEP->getNumOperands() != FirstInst->getNumOperands())
10596 return 0;
10597
Chris Lattner36d3e322009-02-21 00:46:50 +000010598 // Keep track of whether or not all GEPs are of alloca pointers.
10599 if (AllBasePointersAreAllocas &&
10600 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10601 !GEP->hasAllConstantIndices()))
10602 AllBasePointersAreAllocas = false;
10603
Chris Lattner05f18922008-12-01 02:34:36 +000010604 // Compare the operand lists.
10605 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10606 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10607 continue;
10608
10609 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10610 // if one of the PHIs has a constant for the index. The index may be
10611 // substantially cheaper to compute for the constants, so making it a
10612 // variable index could pessimize the path. This also handles the case
10613 // for struct indices, which must always be constant.
10614 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10615 isa<ConstantInt>(GEP->getOperand(op)))
10616 return 0;
10617
10618 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10619 return 0;
10620 FixedOperands[op] = 0; // Needs a PHI.
10621 }
10622 }
10623
Chris Lattner36d3e322009-02-21 00:46:50 +000010624 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010625 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010626 // offset calculation, but all the predecessors will have to materialize the
10627 // stack address into a register anyway. We'd actually rather *clone* the
10628 // load up into the predecessors so that we have a load of a gep of an alloca,
10629 // which can usually all be folded into the load.
10630 if (AllBasePointersAreAllocas)
10631 return 0;
10632
Chris Lattner05f18922008-12-01 02:34:36 +000010633 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10634 // that is variable.
10635 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10636
10637 bool HasAnyPHIs = false;
10638 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10639 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10640 Value *FirstOp = FirstInst->getOperand(i);
10641 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10642 FirstOp->getName()+".pn");
10643 InsertNewInstBefore(NewPN, PN);
10644
10645 NewPN->reserveOperandSpace(e);
10646 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10647 OperandPhis[i] = NewPN;
10648 FixedOperands[i] = NewPN;
10649 HasAnyPHIs = true;
10650 }
10651
10652
10653 // Add all operands to the new PHIs.
10654 if (HasAnyPHIs) {
10655 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10656 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10657 BasicBlock *InBB = PN.getIncomingBlock(i);
10658
10659 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10660 if (PHINode *OpPhi = OperandPhis[op])
10661 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10662 }
10663 }
10664
10665 Value *Base = FixedOperands[0];
10666 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10667 FixedOperands.end());
10668}
10669
10670
Chris Lattner21550882009-02-23 05:56:17 +000010671/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10672/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010673/// obvious the value of the load is not changed from the point of the load to
10674/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010675///
10676/// Finally, it is safe, but not profitable, to sink a load targetting a
10677/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10678/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010679static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010680 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10681
10682 for (++BBI; BBI != E; ++BBI)
10683 if (BBI->mayWriteToMemory())
10684 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010685
10686 // Check for non-address taken alloca. If not address-taken already, it isn't
10687 // profitable to do this xform.
10688 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10689 bool isAddressTaken = false;
10690 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10691 UI != E; ++UI) {
10692 if (isa<LoadInst>(UI)) continue;
10693 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10694 // If storing TO the alloca, then the address isn't taken.
10695 if (SI->getOperand(1) == AI) continue;
10696 }
10697 isAddressTaken = true;
10698 break;
10699 }
10700
Chris Lattner36d3e322009-02-21 00:46:50 +000010701 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010702 return false;
10703 }
10704
Chris Lattner36d3e322009-02-21 00:46:50 +000010705 // If this load is a load from a GEP with a constant offset from an alloca,
10706 // then we don't want to sink it. In its present form, it will be
10707 // load [constant stack offset]. Sinking it will cause us to have to
10708 // materialize the stack addresses in each predecessor in a register only to
10709 // do a shared load from register in the successor.
10710 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10711 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10712 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10713 return false;
10714
Chris Lattner76c73142006-11-01 07:13:54 +000010715 return true;
10716}
10717
Chris Lattner9fe38862003-06-19 17:00:31 +000010718
Chris Lattnerbac32862004-11-14 19:13:23 +000010719// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10720// operator and they all are only used by the PHI, PHI together their
10721// inputs, and do the operation once, to the result of the PHI.
10722Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10723 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10724
10725 // Scan the instruction, looking for input operations that can be folded away.
10726 // If all input operands to the phi are the same instruction (e.g. a cast from
10727 // the same type or "+42") we can pull the operation through the PHI, reducing
10728 // code size and simplifying code.
10729 Constant *ConstantOp = 0;
10730 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010731 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010732 if (isa<CastInst>(FirstInst)) {
10733 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010734 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010735 // Can fold binop, compare or shift here if the RHS is a constant,
10736 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010737 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010738 if (ConstantOp == 0)
10739 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010740 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10741 isVolatile = LI->isVolatile();
10742 // We can't sink the load if the loaded value could be modified between the
10743 // load and the PHI.
10744 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010745 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010746 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010747
10748 // If the PHI is of volatile loads and the load block has multiple
10749 // successors, sinking it would remove a load of the volatile value from
10750 // the path through the other successor.
10751 if (isVolatile &&
10752 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10753 return 0;
10754
Chris Lattner9c080502006-11-01 07:43:41 +000010755 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010756 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010757 } else {
10758 return 0; // Cannot fold this operation.
10759 }
10760
10761 // Check to see if all arguments are the same operation.
10762 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10763 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10764 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010765 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010766 return 0;
10767 if (CastSrcTy) {
10768 if (I->getOperand(0)->getType() != CastSrcTy)
10769 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010770 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010771 // We can't sink the load if the loaded value could be modified between
10772 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010773 if (LI->isVolatile() != isVolatile ||
10774 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010775 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010776 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010777
Chris Lattner71042962008-07-08 17:18:32 +000010778 // If the PHI is of volatile loads and the load block has multiple
10779 // successors, sinking it would remove a load of the volatile value from
10780 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010781 if (isVolatile &&
10782 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10783 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010784
Chris Lattnerbac32862004-11-14 19:13:23 +000010785 } else if (I->getOperand(1) != ConstantOp) {
10786 return 0;
10787 }
10788 }
10789
10790 // Okay, they are all the same operation. Create a new PHI node of the
10791 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010792 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10793 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010794 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010795
10796 Value *InVal = FirstInst->getOperand(0);
10797 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010798
10799 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010800 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10801 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10802 if (NewInVal != InVal)
10803 InVal = 0;
10804 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10805 }
10806
10807 Value *PhiVal;
10808 if (InVal) {
10809 // The new PHI unions all of the same values together. This is really
10810 // common, so we handle it intelligently here for compile-time speed.
10811 PhiVal = InVal;
10812 delete NewPN;
10813 } else {
10814 InsertNewInstBefore(NewPN, PN);
10815 PhiVal = NewPN;
10816 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010817
Chris Lattnerbac32862004-11-14 19:13:23 +000010818 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010819 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010820 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010821 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010822 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010823 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Owen Anderson333c4002009-07-09 23:48:35 +000010824 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010825 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010826 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10827
10828 // If this was a volatile load that we are merging, make sure to loop through
10829 // and mark all the input loads as non-volatile. If we don't do this, we will
10830 // insert a new volatile load and the old ones will not be deletable.
10831 if (isVolatile)
10832 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10833 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10834
10835 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010836}
Chris Lattnera1be5662002-05-02 17:06:02 +000010837
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010838/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10839/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010840static bool DeadPHICycle(PHINode *PN,
10841 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010842 if (PN->use_empty()) return true;
10843 if (!PN->hasOneUse()) return false;
10844
10845 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010846 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010847 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010848
10849 // Don't scan crazily complex things.
10850 if (PotentiallyDeadPHIs.size() == 16)
10851 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010852
10853 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10854 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010855
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010856 return false;
10857}
10858
Chris Lattnercf5008a2007-11-06 21:52:06 +000010859/// PHIsEqualValue - Return true if this phi node is always equal to
10860/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10861/// z = some value; x = phi (y, z); y = phi (x, z)
10862static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10863 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10864 // See if we already saw this PHI node.
10865 if (!ValueEqualPHIs.insert(PN))
10866 return true;
10867
10868 // Don't scan crazily complex things.
10869 if (ValueEqualPHIs.size() == 16)
10870 return false;
10871
10872 // Scan the operands to see if they are either phi nodes or are equal to
10873 // the value.
10874 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10875 Value *Op = PN->getIncomingValue(i);
10876 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10877 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10878 return false;
10879 } else if (Op != NonPhiInVal)
10880 return false;
10881 }
10882
10883 return true;
10884}
10885
10886
Chris Lattner473945d2002-05-06 18:06:38 +000010887// PHINode simplification
10888//
Chris Lattner7e708292002-06-25 16:13:24 +000010889Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010890 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010891 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010892
Owen Anderson7e057142006-07-10 22:03:18 +000010893 if (Value *V = PN.hasConstantValue())
10894 return ReplaceInstUsesWith(PN, V);
10895
Owen Anderson7e057142006-07-10 22:03:18 +000010896 // If all PHI operands are the same operation, pull them through the PHI,
10897 // reducing code size.
10898 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010899 isa<Instruction>(PN.getIncomingValue(1)) &&
10900 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10901 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10902 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10903 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010904 PN.getIncomingValue(0)->hasOneUse())
10905 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10906 return Result;
10907
10908 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10909 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10910 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010911 if (PN.hasOneUse()) {
10912 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10913 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010914 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010915 PotentiallyDeadPHIs.insert(&PN);
10916 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersond672ecb2009-07-03 00:17:18 +000010917 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010918 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010919
10920 // If this phi has a single use, and if that use just computes a value for
10921 // the next iteration of a loop, delete the phi. This occurs with unused
10922 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10923 // common case here is good because the only other things that catch this
10924 // are induction variable analysis (sometimes) and ADCE, which is only run
10925 // late.
10926 if (PHIUser->hasOneUse() &&
10927 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10928 PHIUser->use_back() == &PN) {
Owen Andersond672ecb2009-07-03 00:17:18 +000010929 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010930 }
10931 }
Owen Anderson7e057142006-07-10 22:03:18 +000010932
Chris Lattnercf5008a2007-11-06 21:52:06 +000010933 // We sometimes end up with phi cycles that non-obviously end up being the
10934 // same value, for example:
10935 // z = some value; x = phi (y, z); y = phi (x, z)
10936 // where the phi nodes don't necessarily need to be in the same block. Do a
10937 // quick check to see if the PHI node only contains a single non-phi value, if
10938 // so, scan to see if the phi cycle is actually equal to that value.
10939 {
10940 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10941 // Scan for the first non-phi operand.
10942 while (InValNo != NumOperandVals &&
10943 isa<PHINode>(PN.getIncomingValue(InValNo)))
10944 ++InValNo;
10945
10946 if (InValNo != NumOperandVals) {
10947 Value *NonPhiInVal = PN.getOperand(InValNo);
10948
10949 // Scan the rest of the operands to see if there are any conflicts, if so
10950 // there is no need to recursively scan other phis.
10951 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10952 Value *OpVal = PN.getIncomingValue(InValNo);
10953 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10954 break;
10955 }
10956
10957 // If we scanned over all operands, then we have one unique value plus
10958 // phi values. Scan PHI nodes to see if they all merge in each other or
10959 // the value.
10960 if (InValNo == NumOperandVals) {
10961 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10962 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10963 return ReplaceInstUsesWith(PN, NonPhiInVal);
10964 }
10965 }
10966 }
Chris Lattner60921c92003-12-19 05:58:40 +000010967 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010968}
10969
Reid Spencer17212df2006-12-12 09:18:51 +000010970static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10971 Instruction *InsertPoint,
10972 InstCombiner *IC) {
Dan Gohman6de29f82009-06-15 22:12:54 +000010973 unsigned PtrSize = DTy->getScalarSizeInBits();
10974 unsigned VTySize = V->getType()->getScalarSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010975 // We must cast correctly to the pointer type. Ensure that we
10976 // sign extend the integer value if it is smaller as this is
10977 // used for address computation.
10978 Instruction::CastOps opcode =
10979 (VTySize < PtrSize ? Instruction::SExt :
10980 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10981 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010982}
10983
Chris Lattnera1be5662002-05-02 17:06:02 +000010984
Chris Lattner7e708292002-06-25 16:13:24 +000010985Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010986 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010987 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010988 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010989 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010990 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010991
Chris Lattnere87597f2004-10-16 18:11:37 +000010992 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000010993 return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010994
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010995 bool HasZeroPointerIndex = false;
10996 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10997 HasZeroPointerIndex = C->isNullValue();
10998
10999 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011000 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011001
Chris Lattner28977af2004-04-05 01:30:19 +000011002 // Eliminate unneeded casts for indices.
11003 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011004
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011005 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011006 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11007 i != e; ++i, ++GTI) {
Sanjiv Gupta7787d4a2009-04-24 02:37:54 +000011008 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000011009 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011010 if (CI->getOpcode() == Instruction::ZExt ||
11011 CI->getOpcode() == Instruction::SExt) {
11012 const Type *SrcTy = CI->getOperand(0)->getType();
11013 // We can eliminate a cast from i32 to i64 iff the target
11014 // is a 32-bit pointer target.
Dan Gohman6de29f82009-06-15 22:12:54 +000011015 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011016 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000011017 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000011018 }
11019 }
11020 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011021 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000011022 // to what we need. If narrower, sign-extend it to what we need.
11023 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011024 // insert it. This explicit cast can make subsequent optimizations more
11025 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000011026 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011027 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000011028 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011029 *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000011030 MadeChange = true;
11031 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000011032 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11033 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011034 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011035 MadeChange = true;
11036 }
Dan Gohman4f833d42008-09-11 23:06:38 +000011037 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11038 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011039 *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
Dan Gohman4f833d42008-09-11 23:06:38 +000011040 MadeChange = true;
11041 } else {
11042 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11043 GEP);
11044 *i = Op;
11045 MadeChange = true;
11046 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011047 }
Chris Lattner28977af2004-04-05 01:30:19 +000011048 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011049 }
Chris Lattner28977af2004-04-05 01:30:19 +000011050 if (MadeChange) return &GEP;
11051
Chris Lattner90ac28c2002-08-02 19:29:35 +000011052 // Combine Indices - If the source pointer to this getelementptr instruction
11053 // is a getelementptr instruction, combine the indices of the two
11054 // getelementptr instructions into a single instruction.
11055 //
Chris Lattner72588fc2007-02-15 22:48:32 +000011056 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000011057 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000011058 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000011059
11060 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000011061 // Note that if our source is a gep chain itself that we wait for that
11062 // chain to be resolved before we perform this transformation. This
11063 // avoids us creating a TON of code in some cases.
11064 //
11065 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11066 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11067 return 0; // Wait until our source is folded to completion.
11068
Chris Lattner72588fc2007-02-15 22:48:32 +000011069 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011070
11071 // Find out whether the last index in the source GEP is a sequential idx.
11072 bool EndsWithSequential = false;
11073 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11074 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011075 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011076
Chris Lattner90ac28c2002-08-02 19:29:35 +000011077 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011078 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011079 // Replace: gep (gep %P, long B), long A, ...
11080 // With: T = long A+B; gep %P, T, ...
11081 //
Chris Lattner620ce142004-05-07 22:09:22 +000011082 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011083 if (SO1 == Context->getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011084 Sum = GO1;
Owen Andersond672ecb2009-07-03 00:17:18 +000011085 } else if (GO1 == Context->getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011086 Sum = SO1;
11087 } else {
11088 // If they aren't the same type, convert both to an integer of the
11089 // target's pointer size.
11090 if (SO1->getType() != GO1->getType()) {
11091 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011092 SO1 =
11093 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011094 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011095 GO1 =
11096 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011097 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000011098 unsigned PS = TD->getPointerSizeInBits();
11099 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011100 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011101 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011102
Duncan Sands514ab342007-11-01 20:53:16 +000011103 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011104 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011105 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011106 } else {
11107 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000011108 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11109 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011110 }
11111 }
11112 }
Chris Lattner620ce142004-05-07 22:09:22 +000011113 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Andersond672ecb2009-07-03 00:17:18 +000011114 Sum = Context->getConstantExprAdd(cast<Constant>(SO1),
11115 cast<Constant>(GO1));
Chris Lattner620ce142004-05-07 22:09:22 +000011116 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011117 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011118 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011119 }
Chris Lattner28977af2004-04-05 01:30:19 +000011120 }
Chris Lattner620ce142004-05-07 22:09:22 +000011121
11122 // Recycle the GEP we already have if possible.
11123 if (SrcGEPOperands.size() == 2) {
11124 GEP.setOperand(0, SrcGEPOperands[0]);
11125 GEP.setOperand(1, Sum);
11126 return &GEP;
11127 } else {
11128 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11129 SrcGEPOperands.end()-1);
11130 Indices.push_back(Sum);
11131 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11132 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011133 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011134 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000011135 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011136 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000011137 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11138 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011139 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11140 }
11141
11142 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000011143 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11144 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000011145
Chris Lattner620ce142004-05-07 22:09:22 +000011146 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000011147 // GEP of global variable. If all of the indices for this GEP are
11148 // constants, we can promote this to a constexpr instead of an instruction.
11149
11150 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000011151 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000011152 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11153 for (; I != E && isa<Constant>(*I); ++I)
11154 Indices.push_back(cast<Constant>(*I));
11155
11156 if (I == E) { // If they are all constants...
Owen Andersond672ecb2009-07-03 00:17:18 +000011157 Constant *CE = Context->getConstantExprGetElementPtr(GV,
Chris Lattner55eb1c42007-01-31 04:40:53 +000011158 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000011159
11160 // Replace all uses of the GEP with the new constexpr...
11161 return ReplaceInstUsesWith(GEP, CE);
11162 }
Reid Spencer3da59db2006-11-27 01:05:10 +000011163 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000011164 if (!isa<PointerType>(X->getType())) {
11165 // Not interesting. Source pointer must be a cast from pointer.
11166 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011167 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11168 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011169 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011170 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11171 // into : GEP i8* X, ...
11172 //
Chris Lattnereed48272005-09-13 00:40:14 +000011173 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011174 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11175 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011176 if (const ArrayType *CATy =
11177 dyn_cast<ArrayType>(CPTy->getElementType())) {
11178 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11179 if (CATy->getElementType() == XTy->getElementType()) {
11180 // -> GEP i8* X, ...
11181 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11182 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11183 GEP.getName());
11184 } else if (const ArrayType *XATy =
11185 dyn_cast<ArrayType>(XTy->getElementType())) {
11186 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011187 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011188 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011189 // At this point, we know that the cast source type is a pointer
11190 // to an array of the same type as the destination pointer
11191 // array. Because the array type is never stepped over (there
11192 // is a leading zero) we can fold the cast into this GEP.
11193 GEP.setOperand(0, X);
11194 return &GEP;
11195 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011196 }
11197 }
Chris Lattnereed48272005-09-13 00:40:14 +000011198 } else if (GEP.getNumOperands() == 2) {
11199 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011200 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11201 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011202 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11203 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11204 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011205 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11206 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011207 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011208 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011209 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000011210 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000011211 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011212 // V and GEP are both pointer types --> BitCast
11213 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011214 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011215
11216 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011217 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011218 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011219 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011220
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011221 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011222 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011223 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011224
11225 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11226 // allow either a mul, shift, or constant here.
11227 Value *NewIdx = 0;
11228 ConstantInt *Scale = 0;
11229 if (ArrayEltSize == 1) {
11230 NewIdx = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011231 Scale =
11232 Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011233 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011234 NewIdx = Context->getConstantInt(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011235 Scale = CI;
11236 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11237 if (Inst->getOpcode() == Instruction::Shl &&
11238 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011239 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11240 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersond672ecb2009-07-03 00:17:18 +000011241 Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011242 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011243 NewIdx = Inst->getOperand(0);
11244 } else if (Inst->getOpcode() == Instruction::Mul &&
11245 isa<ConstantInt>(Inst->getOperand(1))) {
11246 Scale = cast<ConstantInt>(Inst->getOperand(1));
11247 NewIdx = Inst->getOperand(0);
11248 }
11249 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011250
Chris Lattner7835cdd2005-09-13 18:36:04 +000011251 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011252 // out, perform the transformation. Note, we don't know whether Scale is
11253 // signed or not. We'll use unsigned version of division/modulo
11254 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011255 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011256 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011257 Scale = Context->getConstantInt(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011258 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011259 if (Scale->getZExtValue() != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011260 Constant *C =
11261 Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011262 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011263 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011264 NewIdx = InsertNewInstBefore(Sc, GEP);
11265 }
11266
11267 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011268 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011269 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011270 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011271 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011272 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011273 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11274 // The NewGEP must be pointer typed, so must the old one -> BitCast
11275 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011276 }
11277 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011278 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011279 }
Chris Lattner58407792009-01-09 04:53:57 +000011280
Chris Lattner46cd5a12009-01-09 05:44:56 +000011281 /// See if we can simplify:
11282 /// X = bitcast A to B*
11283 /// Y = gep X, <...constant indices...>
11284 /// into a gep of the original struct. This is important for SROA and alias
11285 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011286 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011287 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11288 // Determine how much the GEP moves the pointer. We are guaranteed to get
11289 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011290 ConstantInt *OffsetV =
11291 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011292 int64_t Offset = OffsetV->getSExtValue();
11293
11294 // If this GEP instruction doesn't move the pointer, just replace the GEP
11295 // with a bitcast of the real input to the dest type.
11296 if (Offset == 0) {
11297 // If the bitcast is of an allocation, and the allocation will be
11298 // converted to match the type of the cast, don't touch this.
11299 if (isa<AllocationInst>(BCI->getOperand(0))) {
11300 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11301 if (Instruction *I = visitBitCast(*BCI)) {
11302 if (I != BCI) {
11303 I->takeName(BCI);
11304 BCI->getParent()->getInstList().insert(BCI, I);
11305 ReplaceInstUsesWith(*BCI, I);
11306 }
11307 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011308 }
Chris Lattner58407792009-01-09 04:53:57 +000011309 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011310 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011311 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011312
11313 // Otherwise, if the offset is non-zero, we need to find out if there is a
11314 // field at Offset in 'A's type. If so, we can pull the cast through the
11315 // GEP.
11316 SmallVector<Value*, 8> NewIndices;
11317 const Type *InTy =
11318 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011319 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011320 Instruction *NGEP =
11321 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11322 NewIndices.end());
11323 if (NGEP->getType() == GEP.getType()) return NGEP;
11324 InsertNewInstBefore(NGEP, GEP);
11325 NGEP->takeName(&GEP);
11326 return new BitCastInst(NGEP, GEP.getType());
11327 }
Chris Lattner58407792009-01-09 04:53:57 +000011328 }
11329 }
11330
Chris Lattner8a2a3112001-12-14 16:52:21 +000011331 return 0;
11332}
11333
Chris Lattner0864acf2002-11-04 16:18:53 +000011334Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11335 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011336 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011337 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11338 const Type *NewTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000011339 Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011340 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011341
11342 // Create and insert the replacement instruction...
11343 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000011344 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011345 else {
11346 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000011347 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011348 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011349
11350 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011351
Chris Lattner0864acf2002-11-04 16:18:53 +000011352 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011353 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011354 //
11355 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011356 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011357
11358 // Now that I is pointing to the first non-allocation-inst in the block,
11359 // insert our getelementptr instruction...
11360 //
Owen Andersond672ecb2009-07-03 00:17:18 +000011361 Value *NullIdx = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011362 Value *Idx[2];
11363 Idx[0] = NullIdx;
11364 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011365 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11366 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011367
11368 // Now make everything use the getelementptr instead of the original
11369 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011370 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011371 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011372 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011373 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011374 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011375
Dan Gohman6893cd72009-01-13 20:18:38 +000011376 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11377 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011378 // Note that we only do this for alloca's, because malloc should allocate
11379 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011380 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersond672ecb2009-07-03 00:17:18 +000011381 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011382
11383 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11384 if (AI.getAlignment() == 0)
11385 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11386 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011387
Chris Lattner0864acf2002-11-04 16:18:53 +000011388 return 0;
11389}
11390
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011391Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11392 Value *Op = FI.getOperand(0);
11393
Chris Lattner17be6352004-10-18 02:59:09 +000011394 // free undef -> unreachable.
11395 if (isa<UndefValue>(Op)) {
11396 // Insert a new store to null because we cannot modify the CFG here.
Owen Andersond672ecb2009-07-03 00:17:18 +000011397 new StoreInst(Context->getConstantIntTrue(),
11398 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011399 return EraseInstFromFunction(FI);
11400 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011401
Chris Lattner6160e852004-02-28 04:57:37 +000011402 // If we have 'free null' delete the instruction. This can happen in stl code
11403 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011404 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011405 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011406
11407 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11408 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11409 FI.setOperand(0, CI->getOperand(0));
11410 return &FI;
11411 }
11412
11413 // Change free (gep X, 0,0,0,0) into free(X)
11414 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11415 if (GEPI->hasAllZeroIndices()) {
11416 AddToWorkList(GEPI);
11417 FI.setOperand(0, GEPI->getOperand(0));
11418 return &FI;
11419 }
11420 }
11421
11422 // Change free(malloc) into nothing, if the malloc has a single use.
11423 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11424 if (MI->hasOneUse()) {
11425 EraseInstFromFunction(FI);
11426 return EraseInstFromFunction(*MI);
11427 }
Chris Lattner6160e852004-02-28 04:57:37 +000011428
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011429 return 0;
11430}
11431
11432
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011433/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011434static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011435 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011436 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011437 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011438 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011439
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011440 if (TD) {
11441 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11442 // Instead of loading constant c string, use corresponding integer value
11443 // directly if string length is small enough.
11444 std::string Str;
11445 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11446 unsigned len = Str.length();
11447 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11448 unsigned numBits = Ty->getPrimitiveSizeInBits();
11449 // Replace LI with immediate integer store.
11450 if ((numBits >> 3) == len + 1) {
11451 APInt StrVal(numBits, 0);
11452 APInt SingleChar(numBits, 0);
11453 if (TD->isLittleEndian()) {
11454 for (signed i = len-1; i >= 0; i--) {
11455 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11456 StrVal = (StrVal << 8) | SingleChar;
11457 }
11458 } else {
11459 for (unsigned i = 0; i < len; i++) {
11460 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11461 StrVal = (StrVal << 8) | SingleChar;
11462 }
11463 // Append NULL at the end.
11464 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011465 StrVal = (StrVal << 8) | SingleChar;
11466 }
Owen Andersond672ecb2009-07-03 00:17:18 +000011467 Value *NL = Context->getConstantInt(StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011468 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011469 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011470 }
11471 }
11472 }
11473
Mon P Wang6753f952009-02-07 22:19:29 +000011474 const PointerType *DestTy = cast<PointerType>(CI->getType());
11475 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011476 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011477
11478 // If the address spaces don't match, don't eliminate the cast.
11479 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11480 return 0;
11481
Chris Lattnerb89e0712004-07-13 01:49:43 +000011482 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011483
Reid Spencer42230162007-01-22 05:51:25 +000011484 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011485 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011486 // If the source is an array, the code below will not succeed. Check to
11487 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11488 // constants.
11489 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11490 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11491 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011492 Value *Idxs[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011493 Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11494 CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011495 SrcTy = cast<PointerType>(CastOp->getType());
11496 SrcPTy = SrcTy->getElementType();
11497 }
11498
Reid Spencer42230162007-01-22 05:51:25 +000011499 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011500 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011501 // Do not allow turning this into a load of an integer, which is then
11502 // casted to a pointer, this pessimizes pointer analysis a lot.
11503 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000011504 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11505 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011506
Chris Lattnerf9527852005-01-31 04:50:46 +000011507 // Okay, we are casting from one integer or pointer type to another of
11508 // the same size. Instead of casting the pointer before the load, cast
11509 // the result of the loaded value.
11510 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11511 CI->getName(),
11512 LI.isVolatile()),LI);
11513 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011514 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011515 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011516 }
11517 }
11518 return 0;
11519}
11520
Chris Lattner833b8a42003-06-26 05:06:25 +000011521Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11522 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011523
Dan Gohman9941f742007-07-20 16:34:21 +000011524 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011525 unsigned KnownAlign =
11526 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011527 if (KnownAlign >
11528 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11529 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011530 LI.setAlignment(KnownAlign);
11531
Chris Lattner37366c12005-05-01 04:24:53 +000011532 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011533 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011534 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011535 return Res;
11536
11537 // None of the following transforms are legal for volatile loads.
11538 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011539
Dan Gohman2276a7b2008-10-15 23:19:35 +000011540 // Do really simple store-to-load forwarding and load CSE, to catch cases
11541 // where there are several consequtive memory accesses to the same location,
11542 // separated by a few arithmetic operations.
11543 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011544 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11545 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011546
Christopher Lambb15147e2007-12-29 07:56:53 +000011547 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11548 const Value *GEPI0 = GEPI->getOperand(0);
11549 // TODO: Consider a target hook for valid address spaces for this xform.
11550 if (isa<ConstantPointerNull>(GEPI0) &&
11551 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011552 // Insert a new store to null instruction before the load to indicate
11553 // that this code is not reachable. We do this instead of inserting
11554 // an unreachable instruction directly because we cannot modify the
11555 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011556 new StoreInst(Context->getUndef(LI.getType()),
11557 Context->getNullValue(Op->getType()), &LI);
11558 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011559 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011560 }
Chris Lattner37366c12005-05-01 04:24:53 +000011561
Chris Lattnere87597f2004-10-16 18:11:37 +000011562 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011563 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011564 // TODO: Consider a target hook for valid address spaces for this xform.
11565 if (isa<UndefValue>(C) || (C->isNullValue() &&
11566 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011567 // Insert a new store to null instruction before the load to indicate that
11568 // this code is not reachable. We do this instead of inserting an
11569 // unreachable instruction directly because we cannot modify the CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011570 new StoreInst(Context->getUndef(LI.getType()),
11571 Context->getNullValue(Op->getType()), &LI);
11572 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011573 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011574
Chris Lattnere87597f2004-10-16 18:11:37 +000011575 // Instcombine load (constant global) into the value loaded.
11576 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011577 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011578 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011579
Chris Lattnere87597f2004-10-16 18:11:37 +000011580 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011581 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011582 if (CE->getOpcode() == Instruction::GetElementPtr) {
11583 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011584 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011585 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011586 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
11587 Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011588 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011589 if (CE->getOperand(0)->isNullValue()) {
11590 // Insert a new store to null instruction before the load to indicate
11591 // that this code is not reachable. We do this instead of inserting
11592 // an unreachable instruction directly because we cannot modify the
11593 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011594 new StoreInst(Context->getUndef(LI.getType()),
11595 Context->getNullValue(Op->getType()), &LI);
11596 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011597 }
11598
Reid Spencer3da59db2006-11-27 01:05:10 +000011599 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011600 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011601 return Res;
11602 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011603 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011604 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011605
11606 // If this load comes from anywhere in a constant global, and if the global
11607 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011608 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011609 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011610 if (GV->getInitializer()->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +000011611 return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011612 else if (isa<UndefValue>(GV->getInitializer()))
Owen Andersond672ecb2009-07-03 00:17:18 +000011613 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011614 }
11615 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011616
Chris Lattner37366c12005-05-01 04:24:53 +000011617 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011618 // Change select and PHI nodes to select values instead of addresses: this
11619 // helps alias analysis out a lot, allows many others simplifications, and
11620 // exposes redundancy in the code.
11621 //
11622 // Note that we cannot do the transformation unless we know that the
11623 // introduced loads cannot trap! Something like this is valid as long as
11624 // the condition is always false: load (select bool %C, int* null, int* %G),
11625 // but it would not be valid if we transformed it to load from null
11626 // unconditionally.
11627 //
11628 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11629 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011630 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11631 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011632 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011633 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011634 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011635 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011636 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011637 }
11638
Chris Lattner684fe212004-09-23 15:46:00 +000011639 // load (select (cond, null, P)) -> load P
11640 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11641 if (C->isNullValue()) {
11642 LI.setOperand(0, SI->getOperand(2));
11643 return &LI;
11644 }
11645
11646 // load (select (cond, P, null)) -> load P
11647 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11648 if (C->isNullValue()) {
11649 LI.setOperand(0, SI->getOperand(1));
11650 return &LI;
11651 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011652 }
11653 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011654 return 0;
11655}
11656
Reid Spencer55af2b52007-01-19 21:20:31 +000011657/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011658/// when possible. This makes it generally easy to do alias analysis and/or
11659/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011660static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11661 User *CI = cast<User>(SI.getOperand(1));
11662 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011663 LLVMContext *Context = IC.getContext();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011664
11665 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011666 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11667 if (SrcTy == 0) return 0;
11668
11669 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011670
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011671 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11672 return 0;
11673
Chris Lattner3914f722009-01-24 01:00:13 +000011674 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11675 /// to its first element. This allows us to handle things like:
11676 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11677 /// on 32-bit hosts.
11678 SmallVector<Value*, 4> NewGEPIndices;
11679
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011680 // If the source is an array, the code below will not succeed. Check to
11681 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11682 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011683 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11684 // Index through pointer.
Owen Andersond672ecb2009-07-03 00:17:18 +000011685 Constant *Zero = Context->getNullValue(Type::Int32Ty);
Chris Lattner3914f722009-01-24 01:00:13 +000011686 NewGEPIndices.push_back(Zero);
11687
11688 while (1) {
11689 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011690 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011691 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011692 NewGEPIndices.push_back(Zero);
11693 SrcPTy = STy->getElementType(0);
11694 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11695 NewGEPIndices.push_back(Zero);
11696 SrcPTy = ATy->getElementType();
11697 } else {
11698 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011699 }
Chris Lattner3914f722009-01-24 01:00:13 +000011700 }
11701
Owen Andersond672ecb2009-07-03 00:17:18 +000011702 SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011703 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011704
11705 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11706 return 0;
11707
Chris Lattner71759c42009-01-16 20:12:52 +000011708 // If the pointers point into different address spaces or if they point to
11709 // values with different sizes, we can't do the transformation.
11710 if (SrcTy->getAddressSpace() !=
11711 cast<PointerType>(CI->getType())->getAddressSpace() ||
11712 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011713 IC.getTargetData().getTypeSizeInBits(DestPTy))
11714 return 0;
11715
11716 // Okay, we are casting from one integer or pointer type to another of
11717 // the same size. Instead of casting the pointer before
11718 // the store, cast the value to be stored.
11719 Value *NewCast;
11720 Value *SIOp0 = SI.getOperand(0);
11721 Instruction::CastOps opcode = Instruction::BitCast;
11722 const Type* CastSrcTy = SIOp0->getType();
11723 const Type* CastDstTy = SrcPTy;
11724 if (isa<PointerType>(CastDstTy)) {
11725 if (CastSrcTy->isInteger())
11726 opcode = Instruction::IntToPtr;
11727 } else if (isa<IntegerType>(CastDstTy)) {
11728 if (isa<PointerType>(SIOp0->getType()))
11729 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011730 }
Chris Lattner3914f722009-01-24 01:00:13 +000011731
11732 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11733 // emit a GEP to index into its first field.
11734 if (!NewGEPIndices.empty()) {
11735 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000011736 CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner3914f722009-01-24 01:00:13 +000011737 NewGEPIndices.size());
11738 else
11739 CastOp = IC.InsertNewInstBefore(
11740 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11741 NewGEPIndices.end()), SI);
11742 }
11743
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011744 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Andersond672ecb2009-07-03 00:17:18 +000011745 NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011746 else
11747 NewCast = IC.InsertNewInstBefore(
11748 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11749 SI);
11750 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011751}
11752
Chris Lattner4aebaee2008-11-27 08:56:30 +000011753/// equivalentAddressValues - Test if A and B will obviously have the same
11754/// value. This includes recognizing that %t0 and %t1 will have the same
11755/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011756/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011757/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011758/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011759/// %t2 = load i32* %t1
11760///
11761static bool equivalentAddressValues(Value *A, Value *B) {
11762 // Test if the values are trivially equivalent.
11763 if (A == B) return true;
11764
11765 // Test if the values come form identical arithmetic instructions.
11766 if (isa<BinaryOperator>(A) ||
11767 isa<CastInst>(A) ||
11768 isa<PHINode>(A) ||
11769 isa<GetElementPtrInst>(A))
11770 if (Instruction *BI = dyn_cast<Instruction>(B))
11771 if (cast<Instruction>(A)->isIdenticalTo(BI))
11772 return true;
11773
11774 // Otherwise they may not be equivalent.
11775 return false;
11776}
11777
Dale Johannesen4945c652009-03-03 21:26:39 +000011778// If this instruction has two uses, one of which is a llvm.dbg.declare,
11779// return the llvm.dbg.declare.
11780DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11781 if (!V->hasNUses(2))
11782 return 0;
11783 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11784 UI != E; ++UI) {
11785 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11786 return DI;
11787 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11788 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11789 return DI;
11790 }
11791 }
11792 return 0;
11793}
11794
Chris Lattner2f503e62005-01-31 05:36:43 +000011795Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11796 Value *Val = SI.getOperand(0);
11797 Value *Ptr = SI.getOperand(1);
11798
11799 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011800 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011801 ++NumCombined;
11802 return 0;
11803 }
Chris Lattner836692d2007-01-15 06:51:56 +000011804
11805 // If the RHS is an alloca with a single use, zapify the store, making the
11806 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011807 // If the RHS is an alloca with a two uses, the other one being a
11808 // llvm.dbg.declare, zapify the store and the declare, making the
11809 // alloca dead. We must do this to prevent declare's from affecting
11810 // codegen.
11811 if (!SI.isVolatile()) {
11812 if (Ptr->hasOneUse()) {
11813 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011814 EraseInstFromFunction(SI);
11815 ++NumCombined;
11816 return 0;
11817 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011818 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11819 if (isa<AllocaInst>(GEP->getOperand(0))) {
11820 if (GEP->getOperand(0)->hasOneUse()) {
11821 EraseInstFromFunction(SI);
11822 ++NumCombined;
11823 return 0;
11824 }
11825 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11826 EraseInstFromFunction(*DI);
11827 EraseInstFromFunction(SI);
11828 ++NumCombined;
11829 return 0;
11830 }
11831 }
11832 }
11833 }
11834 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11835 EraseInstFromFunction(*DI);
11836 EraseInstFromFunction(SI);
11837 ++NumCombined;
11838 return 0;
11839 }
Chris Lattner836692d2007-01-15 06:51:56 +000011840 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011841
Dan Gohman9941f742007-07-20 16:34:21 +000011842 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011843 unsigned KnownAlign =
11844 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011845 if (KnownAlign >
11846 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11847 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011848 SI.setAlignment(KnownAlign);
11849
Dale Johannesenacb51a32009-03-03 01:43:03 +000011850 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011851 // stores to the same location, separated by a few arithmetic operations. This
11852 // situation often occurs with bitfield accesses.
11853 BasicBlock::iterator BBI = &SI;
11854 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11855 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011856 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011857 // Don't count debug info directives, lest they affect codegen,
11858 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11859 // It is necessary for correctness to skip those that feed into a
11860 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011861 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011862 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011863 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011864 continue;
11865 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011866
11867 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11868 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011869 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11870 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011871 ++NumDeadStore;
11872 ++BBI;
11873 EraseInstFromFunction(*PrevSI);
11874 continue;
11875 }
11876 break;
11877 }
11878
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011879 // If this is a load, we have to stop. However, if the loaded value is from
11880 // the pointer we're loading and is producing the pointer we're storing,
11881 // then *this* store is dead (X = load P; store X -> P).
11882 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011883 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11884 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011885 EraseInstFromFunction(SI);
11886 ++NumCombined;
11887 return 0;
11888 }
11889 // Otherwise, this is a load from some other location. Stores before it
11890 // may not be dead.
11891 break;
11892 }
11893
Chris Lattner9ca96412006-02-08 03:25:32 +000011894 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011895 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011896 break;
11897 }
11898
11899
11900 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011901
11902 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011903 if (isa<ConstantPointerNull>(Ptr) &&
11904 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011905 if (!isa<UndefValue>(Val)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011906 SI.setOperand(0, Context->getUndef(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011907 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011908 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011909 ++NumCombined;
11910 }
11911 return 0; // Do not modify these!
11912 }
11913
11914 // store undef, Ptr -> noop
11915 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011916 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011917 ++NumCombined;
11918 return 0;
11919 }
11920
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011921 // If the pointer destination is a cast, see if we can fold the cast into the
11922 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011923 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011924 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11925 return Res;
11926 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011927 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011928 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11929 return Res;
11930
Chris Lattner408902b2005-09-12 23:23:25 +000011931
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011932 // If this store is the last instruction in the basic block (possibly
11933 // excepting debug info instructions and the pointer bitcasts that feed
11934 // into them), and if the block ends with an unconditional branch, try
11935 // to move it to the successor block.
11936 BBI = &SI;
11937 do {
11938 ++BBI;
11939 } while (isa<DbgInfoIntrinsic>(BBI) ||
11940 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011941 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011942 if (BI->isUnconditional())
11943 if (SimplifyStoreAtEndOfBlock(SI))
11944 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011945
Chris Lattner2f503e62005-01-31 05:36:43 +000011946 return 0;
11947}
11948
Chris Lattner3284d1f2007-04-15 00:07:55 +000011949/// SimplifyStoreAtEndOfBlock - Turn things like:
11950/// if () { *P = v1; } else { *P = v2 }
11951/// into a phi node with a store in the successor.
11952///
Chris Lattner31755a02007-04-15 01:02:18 +000011953/// Simplify things like:
11954/// *P = v1; if () { *P = v2; }
11955/// into a phi node with a store in the successor.
11956///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011957bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11958 BasicBlock *StoreBB = SI.getParent();
11959
11960 // Check to see if the successor block has exactly two incoming edges. If
11961 // so, see if the other predecessor contains a store to the same location.
11962 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011963 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011964
11965 // Determine whether Dest has exactly two predecessors and, if so, compute
11966 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011967 pred_iterator PI = pred_begin(DestBB);
11968 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011969 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011970 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011971 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011972 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011973 return false;
11974
11975 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011976 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011977 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011978 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011979 }
Chris Lattner31755a02007-04-15 01:02:18 +000011980 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011981 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011982
11983 // Bail out if all the relevant blocks aren't distinct (this can happen,
11984 // for example, if SI is in an infinite loop)
11985 if (StoreBB == DestBB || OtherBB == DestBB)
11986 return false;
11987
Chris Lattner31755a02007-04-15 01:02:18 +000011988 // Verify that the other block ends in a branch and is not otherwise empty.
11989 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011990 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011991 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011992 return false;
11993
Chris Lattner31755a02007-04-15 01:02:18 +000011994 // If the other block ends in an unconditional branch, check for the 'if then
11995 // else' case. there is an instruction before the branch.
11996 StoreInst *OtherStore = 0;
11997 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011998 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011999 // Skip over debugging info.
12000 while (isa<DbgInfoIntrinsic>(BBI) ||
12001 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12002 if (BBI==OtherBB->begin())
12003 return false;
12004 --BBI;
12005 }
12006 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012007 OtherStore = dyn_cast<StoreInst>(BBI);
12008 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12009 return false;
12010 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012011 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012012 // destinations is StoreBB, then we have the if/then case.
12013 if (OtherBr->getSuccessor(0) != StoreBB &&
12014 OtherBr->getSuccessor(1) != StoreBB)
12015 return false;
12016
12017 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012018 // if/then triangle. See if there is a store to the same ptr as SI that
12019 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012020 for (;; --BBI) {
12021 // Check to see if we find the matching store.
12022 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12023 if (OtherStore->getOperand(1) != SI.getOperand(1))
12024 return false;
12025 break;
12026 }
Eli Friedman6903a242008-06-13 22:02:12 +000012027 // If we find something that may be using or overwriting the stored
12028 // value, or if we run out of instructions, we can't do the xform.
12029 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012030 BBI == OtherBB->begin())
12031 return false;
12032 }
12033
12034 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012035 // make sure nothing reads or overwrites the stored value in
12036 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012037 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12038 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012039 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012040 return false;
12041 }
12042 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012043
Chris Lattner31755a02007-04-15 01:02:18 +000012044 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012045 Value *MergedVal = OtherStore->getOperand(0);
12046 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012047 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012048 PN->reserveOperandSpace(2);
12049 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012050 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12051 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012052 }
12053
12054 // Advance to a place where it is safe to insert the new store and
12055 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012056 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012057 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12058 OtherStore->isVolatile()), *BBI);
12059
12060 // Nuke the old stores.
12061 EraseInstFromFunction(SI);
12062 EraseInstFromFunction(*OtherStore);
12063 ++NumCombined;
12064 return true;
12065}
12066
Chris Lattner2f503e62005-01-31 05:36:43 +000012067
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012068Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12069 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012070 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012071 BasicBlock *TrueDest;
12072 BasicBlock *FalseDest;
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012073 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012074 !isa<Constant>(X)) {
12075 // Swap Destinations and condition...
12076 BI.setCondition(X);
12077 BI.setSuccessor(0, FalseDest);
12078 BI.setSuccessor(1, TrueDest);
12079 return &BI;
12080 }
12081
Reid Spencere4d87aa2006-12-23 06:05:41 +000012082 // Cannonicalize fcmp_one -> fcmp_oeq
12083 FCmpInst::Predicate FPred; Value *Y;
12084 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012085 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012086 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12087 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12088 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012089 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012090 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012091 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012092 // Swap Destinations and condition...
12093 BI.setCondition(NewSCC);
12094 BI.setSuccessor(0, FalseDest);
12095 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012096 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012097 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012098 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012099 return &BI;
12100 }
12101
12102 // Cannonicalize icmp_ne -> icmp_eq
12103 ICmpInst::Predicate IPred;
12104 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012105 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012106 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12107 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12108 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12109 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012110 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012111 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012112 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000012113 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012114 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012115 BI.setSuccessor(0, FalseDest);
12116 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012117 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012118 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012119 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012120 return &BI;
12121 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012122
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012123 return 0;
12124}
Chris Lattner0864acf2002-11-04 16:18:53 +000012125
Chris Lattner46238a62004-07-03 00:26:11 +000012126Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12127 Value *Cond = SI.getCondition();
12128 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12129 if (I->getOpcode() == Instruction::Add)
12130 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12131 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12132 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012133 SI.setOperand(i,
12134 Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012135 AddRHS));
12136 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000012137 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012138 return &SI;
12139 }
12140 }
12141 return 0;
12142}
12143
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012144Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012145 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012146
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012147 if (!EV.hasIndices())
12148 return ReplaceInstUsesWith(EV, Agg);
12149
12150 if (Constant *C = dyn_cast<Constant>(Agg)) {
12151 if (isa<UndefValue>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012152 return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012153
12154 if (isa<ConstantAggregateZero>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012155 return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012156
12157 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12158 // Extract the element indexed by the first index out of the constant
12159 Value *V = C->getOperand(*EV.idx_begin());
12160 if (EV.getNumIndices() > 1)
12161 // Extract the remaining indices out of the constant indexed by the
12162 // first index
12163 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12164 else
12165 return ReplaceInstUsesWith(EV, V);
12166 }
12167 return 0; // Can't handle other constants
12168 }
12169 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12170 // We're extracting from an insertvalue instruction, compare the indices
12171 const unsigned *exti, *exte, *insi, *inse;
12172 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12173 exte = EV.idx_end(), inse = IV->idx_end();
12174 exti != exte && insi != inse;
12175 ++exti, ++insi) {
12176 if (*insi != *exti)
12177 // The insert and extract both reference distinctly different elements.
12178 // This means the extract is not influenced by the insert, and we can
12179 // replace the aggregate operand of the extract with the aggregate
12180 // operand of the insert. i.e., replace
12181 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12182 // %E = extractvalue { i32, { i32 } } %I, 0
12183 // with
12184 // %E = extractvalue { i32, { i32 } } %A, 0
12185 return ExtractValueInst::Create(IV->getAggregateOperand(),
12186 EV.idx_begin(), EV.idx_end());
12187 }
12188 if (exti == exte && insi == inse)
12189 // Both iterators are at the end: Index lists are identical. Replace
12190 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12191 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12192 // with "i32 42"
12193 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12194 if (exti == exte) {
12195 // The extract list is a prefix of the insert list. i.e. replace
12196 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12197 // %E = extractvalue { i32, { i32 } } %I, 1
12198 // with
12199 // %X = extractvalue { i32, { i32 } } %A, 1
12200 // %E = insertvalue { i32 } %X, i32 42, 0
12201 // by switching the order of the insert and extract (though the
12202 // insertvalue should be left in, since it may have other uses).
12203 Value *NewEV = InsertNewInstBefore(
12204 ExtractValueInst::Create(IV->getAggregateOperand(),
12205 EV.idx_begin(), EV.idx_end()),
12206 EV);
12207 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12208 insi, inse);
12209 }
12210 if (insi == inse)
12211 // The insert list is a prefix of the extract list
12212 // We can simply remove the common indices from the extract and make it
12213 // operate on the inserted value instead of the insertvalue result.
12214 // i.e., replace
12215 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12216 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12217 // with
12218 // %E extractvalue { i32 } { i32 42 }, 0
12219 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12220 exti, exte);
12221 }
12222 // Can't simplify extracts from other values. Note that nested extracts are
12223 // already simplified implicitely by the above (extract ( extract (insert) )
12224 // will be translated into extract ( insert ( extract ) ) first and then just
12225 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012226 return 0;
12227}
12228
Chris Lattner220b0cf2006-03-05 00:22:33 +000012229/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12230/// is to leave as a vector operation.
12231static bool CheapToScalarize(Value *V, bool isConstant) {
12232 if (isa<ConstantAggregateZero>(V))
12233 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012234 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012235 if (isConstant) return true;
12236 // If all elts are the same, we can extract.
12237 Constant *Op0 = C->getOperand(0);
12238 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12239 if (C->getOperand(i) != Op0)
12240 return false;
12241 return true;
12242 }
12243 Instruction *I = dyn_cast<Instruction>(V);
12244 if (!I) return false;
12245
12246 // Insert element gets simplified to the inserted element or is deleted if
12247 // this is constant idx extract element and its a constant idx insertelt.
12248 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12249 isa<ConstantInt>(I->getOperand(2)))
12250 return true;
12251 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12252 return true;
12253 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12254 if (BO->hasOneUse() &&
12255 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12256 CheapToScalarize(BO->getOperand(1), isConstant)))
12257 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012258 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12259 if (CI->hasOneUse() &&
12260 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12261 CheapToScalarize(CI->getOperand(1), isConstant)))
12262 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012263
12264 return false;
12265}
12266
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012267/// Read and decode a shufflevector mask.
12268///
12269/// It turns undef elements into values that are larger than the number of
12270/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012271static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12272 unsigned NElts = SVI->getType()->getNumElements();
12273 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12274 return std::vector<unsigned>(NElts, 0);
12275 if (isa<UndefValue>(SVI->getOperand(2)))
12276 return std::vector<unsigned>(NElts, 2*NElts);
12277
12278 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012279 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012280 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12281 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012282 Result.push_back(NElts*2); // undef -> 8
12283 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012284 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012285 return Result;
12286}
12287
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012288/// FindScalarElement - Given a vector and an element number, see if the scalar
12289/// value is already around as a register, for example if it were inserted then
12290/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012291static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012292 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012293 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12294 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012295 unsigned Width = PTy->getNumElements();
12296 if (EltNo >= Width) // Out of range access.
Owen Andersond672ecb2009-07-03 00:17:18 +000012297 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012298
12299 if (isa<UndefValue>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012300 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012301 else if (isa<ConstantAggregateZero>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012302 return Context->getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012303 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012304 return CP->getOperand(EltNo);
12305 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12306 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012307 if (!isa<ConstantInt>(III->getOperand(2)))
12308 return 0;
12309 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012310
12311 // If this is an insert to the element we are looking for, return the
12312 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012313 if (EltNo == IIElt)
12314 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012315
12316 // Otherwise, the insertelement doesn't modify the value, recurse on its
12317 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012318 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012319 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012320 unsigned LHSWidth =
12321 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012322 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012323 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012324 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012325 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012326 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012327 else
Owen Andersond672ecb2009-07-03 00:17:18 +000012328 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012329 }
12330
12331 // Otherwise, we don't know.
12332 return 0;
12333}
12334
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012335Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012336 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012337 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012338 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012339
Dan Gohman07a96762007-07-16 14:29:03 +000012340 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012341 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012342 return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012343
Reid Spencer9d6565a2007-02-15 02:26:10 +000012344 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012345 // If vector val is constant with all elements the same, replace EI with
12346 // that element. When the elements are not identical, we cannot replace yet
12347 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012348 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012349 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012350 if (C->getOperand(i) != op0) {
12351 op0 = 0;
12352 break;
12353 }
12354 if (op0)
12355 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012356 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000012357
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012358 // If extracting a specified index from the vector, see if we can recursively
12359 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012360 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012361 unsigned IndexVal = IdxC->getZExtValue();
12362 unsigned VectorWidth =
12363 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12364
12365 // If this is extracting an invalid index, turn this into undef, to avoid
12366 // crashing the code below.
12367 if (IndexVal >= VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012368 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012369
Chris Lattner867b99f2006-10-05 06:55:50 +000012370 // This instruction only demands the single element from the input vector.
12371 // If the input vector has a single use, simplify it based on this use
12372 // property.
Chris Lattner85464092007-04-09 01:37:55 +000012373 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012374 APInt UndefElts(VectorWidth, 0);
12375 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012376 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012377 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012378 EI.setOperand(0, V);
12379 return &EI;
12380 }
12381 }
12382
Owen Andersond672ecb2009-07-03 00:17:18 +000012383 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012384 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012385
12386 // If the this extractelement is directly using a bitcast from a vector of
12387 // the same number of elements, see if we can find the source element from
12388 // it. In this case, we will end up needing to bitcast the scalars.
12389 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12390 if (const VectorType *VT =
12391 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12392 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012393 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12394 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012395 return new BitCastInst(Elt, EI.getType());
12396 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012397 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012398
Chris Lattner73fa49d2006-05-25 22:53:38 +000012399 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012400 if (I->hasOneUse()) {
12401 // Push extractelement into predecessor operation if legal and
12402 // profitable to do so
12403 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012404 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12405 if (CheapToScalarize(BO, isConstantElt)) {
12406 ExtractElementInst *newEI0 =
12407 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12408 EI.getName()+".lhs");
12409 ExtractElementInst *newEI1 =
12410 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12411 EI.getName()+".rhs");
12412 InsertNewInstBefore(newEI0, EI);
12413 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012414 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012415 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012416 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012417 unsigned AS =
12418 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012419 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +000012420 Context->getPointerType(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012421 GetElementPtrInst *GEP =
12422 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012423 InsertNewInstBefore(GEP, EI);
12424 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012425 }
12426 }
12427 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12428 // Extracting the inserted element?
12429 if (IE->getOperand(2) == EI.getOperand(1))
12430 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12431 // If the inserted and extracted elements are constants, they must not
12432 // be the same value, extract from the pre-inserted value instead.
12433 if (isa<Constant>(IE->getOperand(2)) &&
12434 isa<Constant>(EI.getOperand(1))) {
12435 AddUsesToWorkList(EI);
12436 EI.setOperand(0, IE->getOperand(0));
12437 return &EI;
12438 }
12439 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12440 // If this is extracting an element from a shufflevector, figure out where
12441 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012442 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12443 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012444 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012445 unsigned LHSWidth =
12446 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12447
12448 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012449 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012450 else if (SrcIdx < LHSWidth*2) {
12451 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012452 Src = SVI->getOperand(1);
12453 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012454 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012455 }
Chris Lattner867b99f2006-10-05 06:55:50 +000012456 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012457 }
12458 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000012459 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012460 return 0;
12461}
12462
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012463/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12464/// elements from either LHS or RHS, return the shuffle mask and true.
12465/// Otherwise, return false.
12466static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012467 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012468 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012469 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12470 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012471 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012472
12473 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012474 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012475 return true;
12476 } else if (V == LHS) {
12477 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012478 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012479 return true;
12480 } else if (V == RHS) {
12481 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012482 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012483 return true;
12484 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12485 // If this is an insert of an extract from some other vector, include it.
12486 Value *VecOp = IEI->getOperand(0);
12487 Value *ScalarOp = IEI->getOperand(1);
12488 Value *IdxOp = IEI->getOperand(2);
12489
Chris Lattnerd929f062006-04-27 21:14:21 +000012490 if (!isa<ConstantInt>(IdxOp))
12491 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012492 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012493
12494 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12495 // Okay, we can handle this if the vector we are insertinting into is
12496 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012497 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012498 // If so, update the mask to reflect the inserted undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012499 Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012500 return true;
12501 }
12502 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12503 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012504 EI->getOperand(0)->getType() == V->getType()) {
12505 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012506 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012507
12508 // This must be extracting from either LHS or RHS.
12509 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12510 // Okay, we can handle this if the vector we are insertinting into is
12511 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012512 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012513 // If so, update the mask to reflect the inserted value.
12514 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012515 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012516 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012517 } else {
12518 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012519 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012520 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012521
12522 }
12523 return true;
12524 }
12525 }
12526 }
12527 }
12528 }
12529 // TODO: Handle shufflevector here!
12530
12531 return false;
12532}
12533
12534/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12535/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12536/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012537static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012538 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012539 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012540 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012541 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012542 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012543
12544 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012545 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012546 return V;
12547 } else if (isa<ConstantAggregateZero>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012548 Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012549 return V;
12550 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12551 // If this is an insert of an extract from some other vector, include it.
12552 Value *VecOp = IEI->getOperand(0);
12553 Value *ScalarOp = IEI->getOperand(1);
12554 Value *IdxOp = IEI->getOperand(2);
12555
12556 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12557 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12558 EI->getOperand(0)->getType() == V->getType()) {
12559 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012560 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12561 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012562
12563 // Either the extracted from or inserted into vector must be RHSVec,
12564 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012565 if (EI->getOperand(0) == RHS || RHS == 0) {
12566 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012567 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012568 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012569 Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012570 return V;
12571 }
12572
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012573 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012574 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12575 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012576 // Everything but the extracted element is replaced with the RHS.
12577 for (unsigned i = 0; i != NumElts; ++i) {
12578 if (i != InsertedIdx)
Owen Andersond672ecb2009-07-03 00:17:18 +000012579 Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012580 }
12581 return V;
12582 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012583
12584 // If this insertelement is a chain that comes from exactly these two
12585 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012586 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12587 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012588 return EI->getOperand(0);
12589
Chris Lattnerefb47352006-04-15 01:39:45 +000012590 }
12591 }
12592 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012593 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012594
12595 // Otherwise, can't do anything fancy. Return an identity vector.
12596 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012597 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012598 return V;
12599}
12600
12601Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12602 Value *VecOp = IE.getOperand(0);
12603 Value *ScalarOp = IE.getOperand(1);
12604 Value *IdxOp = IE.getOperand(2);
12605
Chris Lattner599ded12007-04-09 01:11:16 +000012606 // Inserting an undef or into an undefined place, remove this.
12607 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12608 ReplaceInstUsesWith(IE, VecOp);
12609
Chris Lattnerefb47352006-04-15 01:39:45 +000012610 // If the inserted element was extracted from some other vector, and if the
12611 // indexes are constant, try to turn this into a shufflevector operation.
12612 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12613 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12614 EI->getOperand(0)->getType() == IE.getType()) {
12615 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012616 unsigned ExtractedIdx =
12617 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012618 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012619
12620 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12621 return ReplaceInstUsesWith(IE, VecOp);
12622
12623 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersond672ecb2009-07-03 00:17:18 +000012624 return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012625
12626 // If we are extracting a value from a vector, then inserting it right
12627 // back into the same place, just use the input vector.
12628 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12629 return ReplaceInstUsesWith(IE, VecOp);
12630
12631 // We could theoretically do this for ANY input. However, doing so could
12632 // turn chains of insertelement instructions into a chain of shufflevector
12633 // instructions, and right now we do not merge shufflevectors. As such,
12634 // only do this in a situation where it is clear that there is benefit.
12635 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12636 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12637 // the values of VecOp, except then one read from EIOp0.
12638 // Build a new shuffle mask.
12639 std::vector<Constant*> Mask;
12640 if (isa<UndefValue>(VecOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000012641 Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012642 else {
12643 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Andersond672ecb2009-07-03 00:17:18 +000012644 Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012645 NumVectorElts));
12646 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012647 Mask[InsertedIdx] =
12648 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012649 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersond672ecb2009-07-03 00:17:18 +000012650 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012651 }
12652
12653 // If this insertelement isn't used by some other insertelement, turn it
12654 // (and any insertelements it points to), into one big shuffle.
12655 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12656 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012657 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012658 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12659 if (RHS == 0) RHS = Context->getUndef(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012660 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012661 return new ShuffleVectorInst(LHS, RHS,
12662 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012663 }
12664 }
12665 }
12666
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012667 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12668 APInt UndefElts(VWidth, 0);
12669 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12670 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12671 return &IE;
12672
Chris Lattnerefb47352006-04-15 01:39:45 +000012673 return 0;
12674}
12675
12676
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012677Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12678 Value *LHS = SVI.getOperand(0);
12679 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012680 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012681
12682 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012683
Chris Lattner867b99f2006-10-05 06:55:50 +000012684 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012685 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012686 return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012687
Dan Gohman488fbfc2008-09-09 18:11:14 +000012688 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012689
12690 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12691 return 0;
12692
Evan Cheng388df622009-02-03 10:05:09 +000012693 APInt UndefElts(VWidth, 0);
12694 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12695 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012696 LHS = SVI.getOperand(0);
12697 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012698 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012699 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012700
Chris Lattner863bcff2006-05-25 23:48:38 +000012701 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12702 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12703 if (LHS == RHS || isa<UndefValue>(LHS)) {
12704 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012705 // shuffle(undef,undef,mask) -> undef.
12706 return ReplaceInstUsesWith(SVI, LHS);
12707 }
12708
Chris Lattner863bcff2006-05-25 23:48:38 +000012709 // Remap any references to RHS to use LHS.
12710 std::vector<Constant*> Elts;
12711 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012712 if (Mask[i] >= 2*e)
Owen Andersond672ecb2009-07-03 00:17:18 +000012713 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012714 else {
12715 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012716 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012717 Mask[i] = 2*e; // Turn into undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012718 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman4ce96272008-08-06 18:17:32 +000012719 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012720 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Andersond672ecb2009-07-03 00:17:18 +000012721 Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012722 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012723 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012724 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012725 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +000012726 SVI.setOperand(1, Context->getUndef(RHS->getType()));
12727 SVI.setOperand(2, Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012728 LHS = SVI.getOperand(0);
12729 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012730 MadeChange = true;
12731 }
12732
Chris Lattner7b2e27922006-05-26 00:29:06 +000012733 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012734 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012735
Chris Lattner863bcff2006-05-25 23:48:38 +000012736 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12737 if (Mask[i] >= e*2) continue; // Ignore undef values.
12738 // Is this an identity shuffle of the LHS value?
12739 isLHSID &= (Mask[i] == i);
12740
12741 // Is this an identity shuffle of the RHS value?
12742 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012743 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012744
Chris Lattner863bcff2006-05-25 23:48:38 +000012745 // Eliminate identity shuffles.
12746 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12747 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012748
Chris Lattner7b2e27922006-05-26 00:29:06 +000012749 // If the LHS is a shufflevector itself, see if we can combine it with this
12750 // one without producing an unusual shuffle. Here we are really conservative:
12751 // we are absolutely afraid of producing a shuffle mask not in the input
12752 // program, because the code gen may not be smart enough to turn a merged
12753 // shuffle into two specific shuffles: it may produce worse code. As such,
12754 // we only merge two shuffles if the result is one of the two input shuffle
12755 // masks. In this case, merging the shuffles just removes one instruction,
12756 // which we know is safe. This is good for things like turning:
12757 // (splat(splat)) -> splat.
12758 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12759 if (isa<UndefValue>(RHS)) {
12760 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12761
12762 std::vector<unsigned> NewMask;
12763 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12764 if (Mask[i] >= 2*e)
12765 NewMask.push_back(2*e);
12766 else
12767 NewMask.push_back(LHSMask[Mask[i]]);
12768
12769 // If the result mask is equal to the src shuffle or this shuffle mask, do
12770 // the replacement.
12771 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012772 unsigned LHSInNElts =
12773 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012774 std::vector<Constant*> Elts;
12775 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012776 if (NewMask[i] >= LHSInNElts*2) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012777 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012778 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012779 Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012780 }
12781 }
12782 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12783 LHSSVI->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +000012784 Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012785 }
12786 }
12787 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012788
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012789 return MadeChange ? &SVI : 0;
12790}
12791
12792
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012793
Chris Lattnerea1c4542004-12-08 23:43:58 +000012794
12795/// TryToSinkInstruction - Try to move the specified instruction from its
12796/// current block into the beginning of DestBlock, which can only happen if it's
12797/// safe to move the instruction past all of the instructions between it and the
12798/// end of its block.
12799static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12800 assert(I->hasOneUse() && "Invariants didn't hold!");
12801
Chris Lattner108e9022005-10-27 17:13:11 +000012802 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012803 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012804 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012805
Chris Lattnerea1c4542004-12-08 23:43:58 +000012806 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012807 if (isa<AllocaInst>(I) && I->getParent() ==
12808 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012809 return false;
12810
Chris Lattner96a52a62004-12-09 07:14:34 +000012811 // We can only sink load instructions if there is nothing between the load and
12812 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012813 if (I->mayReadFromMemory()) {
12814 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012815 Scan != E; ++Scan)
12816 if (Scan->mayWriteToMemory())
12817 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012818 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012819
Dan Gohman02dea8b2008-05-23 21:05:58 +000012820 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012821
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012822 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012823 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012824 ++NumSunkInst;
12825 return true;
12826}
12827
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012828
12829/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12830/// all reachable code to the worklist.
12831///
12832/// This has a couple of tricks to make the code faster and more powerful. In
12833/// particular, we constant fold and DCE instructions as we go, to avoid adding
12834/// them to the worklist (this significantly speeds up instcombine on code where
12835/// many instructions are dead or constant). Additionally, if we find a branch
12836/// whose condition is a known constant, we only visit the reachable successors.
12837///
12838static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012839 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012840 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012841 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012842 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012843 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012844
Chris Lattner2c7718a2007-03-23 19:17:18 +000012845 while (!Worklist.empty()) {
12846 BB = Worklist.back();
12847 Worklist.pop_back();
12848
12849 // We have now visited this block! If we've already been here, ignore it.
12850 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012851
12852 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012853 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12854 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012855
Chris Lattner2c7718a2007-03-23 19:17:18 +000012856 // DCE instruction if trivially dead.
12857 if (isInstructionTriviallyDead(Inst)) {
12858 ++NumDeadInst;
12859 DOUT << "IC: DCE: " << *Inst;
12860 Inst->eraseFromParent();
12861 continue;
12862 }
12863
12864 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012865 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000012866 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12867 Inst->replaceAllUsesWith(C);
12868 ++NumConstProp;
12869 Inst->eraseFromParent();
12870 continue;
12871 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012872
Devang Patel7fe1dec2008-11-19 18:56:50 +000012873 // If there are two consecutive llvm.dbg.stoppoint calls then
12874 // it is likely that the optimizer deleted code in between these
12875 // two intrinsics.
12876 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12877 if (DBI_Next) {
12878 if (DBI_Prev
12879 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12880 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12881 IC.RemoveFromWorkList(DBI_Prev);
12882 DBI_Prev->eraseFromParent();
12883 }
12884 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012885 } else {
12886 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012887 }
12888
Chris Lattner2c7718a2007-03-23 19:17:18 +000012889 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012890 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012891
12892 // Recursively visit successors. If this is a branch or switch on a
12893 // constant, only visit the reachable successor.
12894 TerminatorInst *TI = BB->getTerminator();
12895 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12896 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12897 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012898 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012899 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012900 continue;
12901 }
12902 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12903 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12904 // See if this is an explicit destination.
12905 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12906 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012907 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012908 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012909 continue;
12910 }
12911
12912 // Otherwise it is the default destination.
12913 Worklist.push_back(SI->getSuccessor(0));
12914 continue;
12915 }
12916 }
12917
12918 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12919 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012920 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012921}
12922
Chris Lattnerec9c3582007-03-03 02:04:50 +000012923bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012924 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000012925 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012926
12927 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12928 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012929
Chris Lattnerb3d59702005-07-07 20:40:38 +000012930 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012931 // Do a depth-first traversal of the function, populate the worklist with
12932 // the reachable instructions. Ignore blocks that are not reachable. Keep
12933 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012934 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012935 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012936
Chris Lattnerb3d59702005-07-07 20:40:38 +000012937 // Do a quick scan over the function. If we find any blocks that are
12938 // unreachable, remove any instructions inside of them. This prevents
12939 // the instcombine code from having to deal with some bad special cases.
12940 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12941 if (!Visited.count(BB)) {
12942 Instruction *Term = BB->getTerminator();
12943 while (Term != BB->begin()) { // Remove instrs bottom-up
12944 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012945
Bill Wendlingb7427032006-11-26 09:46:52 +000012946 DOUT << "IC: DCE: " << *I;
Dale Johannesenff278b12009-03-10 21:19:49 +000012947 // A debug intrinsic shouldn't force another iteration if we weren't
12948 // going to do one without it.
12949 if (!isa<DbgInfoIntrinsic>(I)) {
12950 ++NumDeadInst;
12951 Changed = true;
12952 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012953 if (!I->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000012954 I->replaceAllUsesWith(Context->getUndef(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012955 I->eraseFromParent();
12956 }
12957 }
12958 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012959
Chris Lattnerdbab3862007-03-02 21:28:56 +000012960 while (!Worklist.empty()) {
12961 Instruction *I = RemoveOneFromWorkList();
12962 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012963
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012964 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012965 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012966 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012967 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012968 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012969 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012970
Bill Wendlingb7427032006-11-26 09:46:52 +000012971 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012972
12973 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012974 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012975 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012976 continue;
12977 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012978
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012979 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012980 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012981 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012982
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012983 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012984 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000012985 ReplaceInstUsesWith(*I, C);
12986
Chris Lattner62b14df2002-09-02 04:59:56 +000012987 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012988 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012989 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012990 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012991 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012992 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012993
Dan Gohman31e4c772009-05-07 19:43:39 +000012994 if (TD &&
12995 (I->getType()->getTypeID() == Type::VoidTyID ||
12996 I->isTrapping())) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012997 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012998 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12999 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000013000 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13001 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000013002 if (NewC != CE) {
13003 i->set(NewC);
13004 Changed = true;
13005 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013006 }
13007
Chris Lattnerea1c4542004-12-08 23:43:58 +000013008 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013009 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013010 BasicBlock *BB = I->getParent();
13011 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13012 if (UserParent != BB) {
13013 bool UserIsSuccessor = false;
13014 // See if the user is one of our successors.
13015 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13016 if (*SI == UserParent) {
13017 UserIsSuccessor = true;
13018 break;
13019 }
13020
13021 // If the user is one of our immediate successors, and if that successor
13022 // only has us as a predecessors (we'd have to split the critical edge
13023 // otherwise), we can keep going.
13024 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13025 next(pred_begin(UserParent)) == pred_end(UserParent))
13026 // Okay, the CFG is simple enough, try to sink this instruction.
13027 Changed |= TryToSinkInstruction(I, UserParent);
13028 }
13029 }
13030
Chris Lattner8a2a3112001-12-14 16:52:21 +000013031 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000013032#ifndef NDEBUG
13033 std::string OrigI;
13034#endif
13035 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000013036 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013037 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013038 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013039 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013040 DOUT << "IC: Old = " << *I
13041 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000013042
Chris Lattnerf523d062004-06-09 05:08:07 +000013043 // Everything uses the new instruction now.
13044 I->replaceAllUsesWith(Result);
13045
13046 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013047 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000013048 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013049
Chris Lattner6934a042007-02-11 01:23:03 +000013050 // Move the name to the new instruction first.
13051 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013052
13053 // Insert the new instruction into the basic block...
13054 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013055 BasicBlock::iterator InsertPos = I;
13056
13057 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13058 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13059 ++InsertPos;
13060
13061 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013062
Chris Lattner00d51312004-05-01 23:27:23 +000013063 // Make sure that we reprocess all operands now that we reduced their
13064 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013065 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000013066
Chris Lattnerf523d062004-06-09 05:08:07 +000013067 // Instructions can end up on the worklist more than once. Make sure
13068 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013069 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013070
13071 // Erase the old instruction.
13072 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000013073 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013074#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000013075 DOUT << "IC: Mod = " << OrigI
13076 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000013077#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013078
Chris Lattner90ac28c2002-08-02 19:29:35 +000013079 // If the instruction was modified, it's possible that it is now dead.
13080 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013081 if (isInstructionTriviallyDead(I)) {
13082 // Make sure we process all operands now that we are reducing their
13083 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000013084 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000013085
Chris Lattner00d51312004-05-01 23:27:23 +000013086 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013087 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013088 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000013089 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000013090 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000013091 AddToWorkList(I);
13092 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013093 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013094 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013095 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013096 }
13097 }
13098
Chris Lattnerec9c3582007-03-03 02:04:50 +000013099 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000013100
13101 // Do an explicit clear, this shrinks the map if needed.
13102 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013103 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013104}
13105
Chris Lattnerec9c3582007-03-03 02:04:50 +000013106
13107bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013108 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13109
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}