blob: 1c25bec304b004fe4e2e6eb12f286c27d489381c [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner173234a2008-06-02 01:18:21 +000045#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000046#include "llvm/Target/TargetData.h"
47#include "llvm/Transforms/Utils/BasicBlockUtils.h"
48#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000050#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000051#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000052#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000053#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000054#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000055#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000056#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000057#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000058#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000059#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000060#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000061#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000062#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000063#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000064#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000065#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000066using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000067using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000068
Chris Lattner0e5f4992006-12-19 21:40:18 +000069STATISTIC(NumCombined , "Number of insts combined");
70STATISTIC(NumConstProp, "Number of constant folds");
71STATISTIC(NumDeadInst , "Number of dead inst eliminated");
72STATISTIC(NumDeadStore, "Number of dead stores eliminated");
73STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000074
Chris Lattner0e5f4992006-12-19 21:40:18 +000075namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000076 class VISIBILITY_HIDDEN InstCombiner
77 : public FunctionPass,
78 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000079 // Worklist of all of the instructions that need to be simplified.
Chris Lattner2806dff2008-08-15 04:03:01 +000080 SmallVector<Instruction*, 256> Worklist;
Chris Lattnerdbab3862007-03-02 21:28:56 +000081 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000082 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000083 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000084 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000085 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000086 InstCombiner() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000087
Owen Anderson07cf79e2009-07-06 23:00:19 +000088 LLVMContext *getContext() { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +000089
Chris Lattnerdbab3862007-03-02 21:28:56 +000090 /// AddToWorkList - Add the specified instruction to the worklist if it
91 /// isn't already in it.
92 void AddToWorkList(Instruction *I) {
Dan Gohman6b345ee2008-07-07 17:46:23 +000093 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerdbab3862007-03-02 21:28:56 +000094 Worklist.push_back(I);
95 }
96
97 // RemoveFromWorkList - remove I from the worklist if it exists.
98 void RemoveFromWorkList(Instruction *I) {
99 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
100 if (It == WorklistMap.end()) return; // Not in worklist.
101
102 // Don't bother moving everything down, just null out the slot.
103 Worklist[It->second] = 0;
104
105 WorklistMap.erase(It);
106 }
107
108 Instruction *RemoveOneFromWorkList() {
109 Instruction *I = Worklist.back();
110 Worklist.pop_back();
111 WorklistMap.erase(I);
112 return I;
113 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000114
Chris Lattnerdbab3862007-03-02 21:28:56 +0000115
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000116 /// AddUsersToWorkList - When an instruction is simplified, add all users of
117 /// the instruction to the work lists because they might get more simplified
118 /// now.
119 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000120 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000121 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000122 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000123 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000124 }
125
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000126 /// AddUsesToWorkList - When an instruction is simplified, add operands to
127 /// the work lists because they might get more simplified now.
128 ///
129 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000130 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
131 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000132 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000133 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000134
135 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
136 /// dead. Add all of its operands to the worklist, turning them into
137 /// undef's to reduce the number of uses of those instructions.
138 ///
139 /// Return the specified operand before it is turned into an undef.
140 ///
141 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
142 Value *R = I.getOperand(op);
143
Gabor Greif177dd3f2008-06-12 21:37:33 +0000144 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
145 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000146 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000147 // Set the operand to undef to drop the use.
Owen Andersond672ecb2009-07-03 00:17:18 +0000148 *i = Context->getUndef(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000149 }
150
151 return R;
152 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000153
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000154 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000155 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000156
157 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000158
Chris Lattner97e52e42002-04-28 21:27:06 +0000159 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000160 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000161 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000162 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000163 }
164
Chris Lattner28977af2004-04-05 01:30:19 +0000165 TargetData &getTargetData() const { return *TD; }
166
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000167 // Visitation implementation - Implement instruction combining for different
168 // instruction types. The semantics are as follows:
169 // Return Value:
170 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000171 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000172 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000173 //
Chris Lattner7e708292002-06-25 16:13:24 +0000174 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000175 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000176 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000177 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000178 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000179 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000180 Instruction *visitURem(BinaryOperator &I);
181 Instruction *visitSRem(BinaryOperator &I);
182 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000183 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000184 Instruction *commonRemTransforms(BinaryOperator &I);
185 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000186 Instruction *commonDivTransforms(BinaryOperator &I);
187 Instruction *commonIDivTransforms(BinaryOperator &I);
188 Instruction *visitUDiv(BinaryOperator &I);
189 Instruction *visitSDiv(BinaryOperator &I);
190 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000191 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000192 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000193 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000194 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000195 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000196 Instruction *visitOr (BinaryOperator &I);
197 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000198 Instruction *visitShl(BinaryOperator &I);
199 Instruction *visitAShr(BinaryOperator &I);
200 Instruction *visitLShr(BinaryOperator &I);
201 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000202 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
203 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000204 Instruction *visitFCmpInst(FCmpInst &I);
205 Instruction *visitICmpInst(ICmpInst &I);
206 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000207 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
208 Instruction *LHS,
209 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000210 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
211 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000212
Reid Spencere4d87aa2006-12-23 06:05:41 +0000213 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
214 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000215 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000216 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000217 Instruction *commonCastTransforms(CastInst &CI);
218 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000219 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000220 Instruction *visitTrunc(TruncInst &CI);
221 Instruction *visitZExt(ZExtInst &CI);
222 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000223 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000224 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000225 Instruction *visitFPToUI(FPToUIInst &FI);
226 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000227 Instruction *visitUIToFP(CastInst &CI);
228 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000229 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000230 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000231 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000232 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
233 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000234 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000235 Instruction *visitSelectInst(SelectInst &SI);
236 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000237 Instruction *visitCallInst(CallInst &CI);
238 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000239 Instruction *visitPHINode(PHINode &PN);
240 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000241 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000242 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000243 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000244 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000245 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000246 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000247 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000248 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000249 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000250 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000251
252 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000253 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000254
Chris Lattner9fe38862003-06-19 17:00:31 +0000255 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000256 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000257 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000258 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000259 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
260 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000261 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000262 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
263
Chris Lattner9fe38862003-06-19 17:00:31 +0000264
Chris Lattner28977af2004-04-05 01:30:19 +0000265 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000266 // InsertNewInstBefore - insert an instruction New before instruction Old
267 // in the program. Add the new instruction to the worklist.
268 //
Chris Lattner955f3312004-09-28 21:48:02 +0000269 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000270 assert(New && New->getParent() == 0 &&
271 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000272 BasicBlock *BB = Old.getParent();
273 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000274 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000275 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000276 }
277
Chris Lattner0c967662004-09-24 15:21:34 +0000278 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
279 /// This also adds the cast to the worklist. Finally, this returns the
280 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000281 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
282 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000283 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000284
Chris Lattnere2ed0572006-04-06 19:19:17 +0000285 if (Constant *CV = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000286 return Context->getConstantExprCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000287
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000288 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000289 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000290 return C;
291 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000292
293 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
294 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
295 }
296
Chris Lattner0c967662004-09-24 15:21:34 +0000297
Chris Lattner8b170942002-08-09 23:47:40 +0000298 // ReplaceInstUsesWith - This method is to be used when an instruction is
299 // found to be dead, replacable with another preexisting expression. Here
300 // we add all uses of I to the worklist, replace all uses of I with the new
301 // value, then return I, so that the inst combiner will know that I was
302 // modified.
303 //
304 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000305 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000306 if (&I != V) {
307 I.replaceAllUsesWith(V);
308 return &I;
309 } else {
310 // If we are replacing the instruction with itself, this must be in a
311 // segment of unreachable code, so just clobber the instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +0000312 I.replaceAllUsesWith(Context->getUndef(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000313 return &I;
314 }
Chris Lattner8b170942002-08-09 23:47:40 +0000315 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000316
317 // EraseInstFromFunction - When dealing with an instruction that has side
318 // effects or produces a void value, we can't rely on DCE to delete the
319 // instruction. Instead, visit methods should return the value returned by
320 // this function.
321 Instruction *EraseInstFromFunction(Instruction &I) {
322 assert(I.use_empty() && "Cannot erase instruction that is used!");
323 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000324 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000325 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000326 return 0; // Don't do anything with FI
327 }
Chris Lattner173234a2008-06-02 01:18:21 +0000328
329 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
330 APInt &KnownOne, unsigned Depth = 0) const {
331 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
332 }
333
334 bool MaskedValueIsZero(Value *V, const APInt &Mask,
335 unsigned Depth = 0) const {
336 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
337 }
338 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
339 return llvm::ComputeNumSignBits(Op, TD, Depth);
340 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000341
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000342 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000343
Reid Spencere4d87aa2006-12-23 06:05:41 +0000344 /// SimplifyCommutative - This performs a few simplifications for
345 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000346 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000347
Reid Spencere4d87aa2006-12-23 06:05:41 +0000348 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
349 /// most-complex to least-complex order.
350 bool SimplifyCompare(CmpInst &I);
351
Chris Lattner886ab6c2009-01-31 08:15:18 +0000352 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
353 /// based on the demanded bits.
354 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
355 APInt& KnownZero, APInt& KnownOne,
356 unsigned Depth);
357 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000358 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000359 unsigned Depth=0);
360
361 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
362 /// SimplifyDemandedBits knows about. See if the instruction has any
363 /// properties that allow us to simplify its operands.
364 bool SimplifyDemandedInstructionBits(Instruction &Inst);
365
Evan Cheng388df622009-02-03 10:05:09 +0000366 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
367 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000368
Chris Lattner4e998b22004-09-29 05:07:12 +0000369 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
370 // PHI node as operand #0, see if we can fold the instruction into the PHI
371 // (which is only possible if all operands to the PHI are constants).
372 Instruction *FoldOpIntoPhi(Instruction &I);
373
Chris Lattnerbac32862004-11-14 19:13:23 +0000374 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
375 // operator and they all are only used by the PHI, PHI together their
376 // inputs, and do the operation once, to the result of the PHI.
377 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000378 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000379 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
380
Chris Lattner7da52b22006-11-01 04:51:18 +0000381
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000382 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
383 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000384
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000385 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000386 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000387 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000388 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000389 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000390 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000391 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000392 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000393 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000394
Chris Lattnerafe91a52006-06-15 19:07:26 +0000395
Reid Spencerc55b2432006-12-13 18:21:21 +0000396 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000397
Dan Gohman6de29f82009-06-15 22:12:54 +0000398 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000399 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000400 unsigned GetOrEnforceKnownAlignment(Value *V,
401 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000402
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000403 };
404}
405
Dan Gohman844731a2008-05-13 00:00:25 +0000406char InstCombiner::ID = 0;
407static RegisterPass<InstCombiner>
408X("instcombine", "Combine redundant instructions");
409
Chris Lattner4f98c562003-03-10 21:43:22 +0000410// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000411// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Owen Anderson0a5372e2009-07-13 04:09:18 +0000412static unsigned getComplexity(LLVMContext *Context, Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000413 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000414 if (BinaryOperator::isNeg(V) ||
415 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000416 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000417 return 3;
418 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000419 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000420 if (isa<Argument>(V)) return 3;
421 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000422}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000423
Chris Lattnerc8802d22003-03-11 00:12:48 +0000424// isOnlyUse - Return true if this instruction will be deleted if we stop using
425// it.
426static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000427 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000428}
429
Chris Lattner4cb170c2004-02-23 06:38:22 +0000430// getPromotedType - Return the specified type promoted as it would be to pass
431// though a va_arg area...
432static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000433 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
434 if (ITy->getBitWidth() < 32)
435 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000436 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000437 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000438}
439
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000440/// getBitCastOperand - If the specified operand is a CastInst, a constant
441/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
442/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000443static Value *getBitCastOperand(Value *V) {
444 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000445 // BitCastInst?
Chris Lattnereed48272005-09-13 00:40:14 +0000446 return I->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000447 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
448 // GetElementPtrInst?
449 if (GEP->hasAllZeroIndices())
450 return GEP->getOperand(0);
451 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000452 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000453 // BitCast ConstantExp?
Chris Lattnereed48272005-09-13 00:40:14 +0000454 return CE->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000455 else if (CE->getOpcode() == Instruction::GetElementPtr) {
456 // GetElementPtr ConstantExp?
457 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
458 I != E; ++I) {
459 ConstantInt *CI = dyn_cast<ConstantInt>(I);
460 if (!CI || !CI->isZero())
461 // Any non-zero indices? Not cast-like.
462 return 0;
463 }
464 // All-zero indices? This is just like casting.
465 return CE->getOperand(0);
466 }
467 }
Chris Lattnereed48272005-09-13 00:40:14 +0000468 return 0;
469}
470
Reid Spencer3da59db2006-11-27 01:05:10 +0000471/// This function is a wrapper around CastInst::isEliminableCastPair. It
472/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000473static Instruction::CastOps
474isEliminableCastPair(
475 const CastInst *CI, ///< The first cast instruction
476 unsigned opcode, ///< The opcode of the second cast instruction
477 const Type *DstTy, ///< The target type for the second cast instruction
478 TargetData *TD ///< The target data for pointer size
479) {
480
481 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
482 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000483
Reid Spencer3da59db2006-11-27 01:05:10 +0000484 // Get the opcodes of the two Cast instructions
485 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
486 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000487
Chris Lattnera0e69692009-03-24 18:35:40 +0000488 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
489 DstTy, TD->getIntPtrType());
490
491 // We don't want to form an inttoptr or ptrtoint that converts to an integer
492 // type that differs from the pointer size.
493 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
494 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
495 Res = 0;
496
497 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000498}
499
500/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
501/// in any code being generated. It does not require codegen if V is simple
502/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000503static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
504 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000505 if (V->getType() == Ty || isa<Constant>(V)) return false;
506
Chris Lattner01575b72006-05-25 23:24:33 +0000507 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000508 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000509 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000510 return false;
511 return true;
512}
513
Chris Lattner4f98c562003-03-10 21:43:22 +0000514// SimplifyCommutative - This performs a few simplifications for commutative
515// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000516//
Chris Lattner4f98c562003-03-10 21:43:22 +0000517// 1. Order operands such that they are listed from right (least complex) to
518// left (most complex). This puts constants before unary operators before
519// binary operators.
520//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000521// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
522// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000523//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000524bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000525 bool Changed = false;
Owen Anderson0a5372e2009-07-13 04:09:18 +0000526 if (getComplexity(Context, I.getOperand(0)) <
527 getComplexity(Context, I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000528 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000529
Chris Lattner4f98c562003-03-10 21:43:22 +0000530 if (!I.isAssociative()) return Changed;
531 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000532 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
533 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
534 if (isa<Constant>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000535 Constant *Folded = Context->getConstantExpr(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000536 cast<Constant>(I.getOperand(1)),
537 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000538 I.setOperand(0, Op->getOperand(0));
539 I.setOperand(1, Folded);
540 return true;
541 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
542 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
543 isOnlyUse(Op) && isOnlyUse(Op1)) {
544 Constant *C1 = cast<Constant>(Op->getOperand(1));
545 Constant *C2 = cast<Constant>(Op1->getOperand(1));
546
547 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersond672ecb2009-07-03 00:17:18 +0000548 Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000549 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000550 Op1->getOperand(0),
551 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000552 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000553 I.setOperand(0, New);
554 I.setOperand(1, Folded);
555 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000556 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000557 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000558 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000559}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000560
Reid Spencere4d87aa2006-12-23 06:05:41 +0000561/// SimplifyCompare - For a CmpInst this function just orders the operands
562/// so that theyare listed from right (least complex) to left (most complex).
563/// This puts constants before unary operators before binary operators.
564bool InstCombiner::SimplifyCompare(CmpInst &I) {
Owen Anderson0a5372e2009-07-13 04:09:18 +0000565 if (getComplexity(Context, I.getOperand(0)) >=
566 getComplexity(Context, I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000567 return false;
568 I.swapOperands();
569 // Compare instructions are not associative so there's nothing else we can do.
570 return true;
571}
572
Chris Lattner8d969642003-03-10 23:06:50 +0000573// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
574// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000575//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000576static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000577 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000578 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000579
Chris Lattner0ce85802004-12-14 20:08:06 +0000580 // Constants can be considered to be negated values if they can be folded.
581 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000582 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000583
584 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
585 if (C->getType()->getElementType()->isInteger())
Owen Andersond672ecb2009-07-03 00:17:18 +0000586 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000587
Chris Lattner8d969642003-03-10 23:06:50 +0000588 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000589}
590
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000591// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
592// instruction if the LHS is a constant negative zero (which is the 'negate'
593// form).
594//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000595static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000596 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000597 return BinaryOperator::getFNegArgument(V);
598
599 // Constants can be considered to be negated values if they can be folded.
600 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000601 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000602
603 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
604 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersond672ecb2009-07-03 00:17:18 +0000605 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000606
607 return 0;
608}
609
Owen Anderson07cf79e2009-07-06 23:00:19 +0000610static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
Chris Lattner8d969642003-03-10 23:06:50 +0000611 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000612 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000613
614 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000615 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000616 return Context->getConstantInt(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000617 return 0;
618}
619
Chris Lattnerc8802d22003-03-11 00:12:48 +0000620// dyn_castFoldableMul - If this value is a multiply that can be folded into
621// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000622// non-constant operand of the multiply, and set CST to point to the multiplier.
623// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000624//
Owen Andersond672ecb2009-07-03 00:17:18 +0000625static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000626 LLVMContext *Context) {
Chris Lattner42a75512007-01-15 02:27:26 +0000627 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000628 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000629 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000630 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000631 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000632 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000633 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000634 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000635 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000636 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Owen Andersond672ecb2009-07-03 00:17:18 +0000637 CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000638 return I->getOperand(0);
639 }
640 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000641 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000642}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000643
Chris Lattner574da9b2005-01-13 20:14:25 +0000644/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
645/// expression, return it.
646static User *dyn_castGetElementPtr(Value *V) {
647 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
648 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
649 if (CE->getOpcode() == Instruction::GetElementPtr)
650 return cast<User>(V);
651 return false;
652}
653
Reid Spencer7177c3a2007-03-25 05:33:51 +0000654/// AddOne - Add one to a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000655static Constant *AddOne(Constant *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000656 return Context->getConstantExprAdd(C,
657 Context->getConstantInt(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000658}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000659/// SubOne - Subtract one from a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000660static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000661 return Context->getConstantExprSub(C,
662 Context->getConstantInt(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000663}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000664/// MultiplyOverflows - True if the multiply can not be expressed in an int
665/// this size.
Owen Andersond672ecb2009-07-03 00:17:18 +0000666static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000667 LLVMContext *Context) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000668 uint32_t W = C1->getBitWidth();
669 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
670 if (sign) {
671 LHSExt.sext(W * 2);
672 RHSExt.sext(W * 2);
673 } else {
674 LHSExt.zext(W * 2);
675 RHSExt.zext(W * 2);
676 }
677
678 APInt MulExt = LHSExt * RHSExt;
679
680 if (sign) {
681 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
682 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
683 return MulExt.slt(Min) || MulExt.sgt(Max);
684 } else
685 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
686}
Chris Lattner955f3312004-09-28 21:48:02 +0000687
Reid Spencere7816b52007-03-08 01:52:58 +0000688
Chris Lattner255d8912006-02-11 09:31:47 +0000689/// ShrinkDemandedConstant - Check to see if the specified operand of the
690/// specified instruction is a constant integer. If so, check to see if there
691/// are any bits set in the constant that are not demanded. If so, shrink the
692/// constant and return true.
693static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000694 APInt Demanded, LLVMContext *Context) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000695 assert(I && "No instruction?");
696 assert(OpNo < I->getNumOperands() && "Operand index too large");
697
698 // If the operand is not a constant integer, nothing to do.
699 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
700 if (!OpC) return false;
701
702 // If there are no bits set that aren't demanded, nothing to do.
703 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
704 if ((~Demanded & OpC->getValue()) == 0)
705 return false;
706
707 // This instruction is producing bits that are not demanded. Shrink the RHS.
708 Demanded &= OpC->getValue();
Owen Andersond672ecb2009-07-03 00:17:18 +0000709 I->setOperand(OpNo, Context->getConstantInt(Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000710 return true;
711}
712
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000713// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
714// set of known zero and one bits, compute the maximum and minimum values that
715// could have the specified known zero and known one bits, returning them in
716// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000717static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000718 const APInt& KnownOne,
719 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000720 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
721 KnownZero.getBitWidth() == Min.getBitWidth() &&
722 KnownZero.getBitWidth() == Max.getBitWidth() &&
723 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000724 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000725
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000726 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
727 // bit if it is unknown.
728 Min = KnownOne;
729 Max = KnownOne|UnknownBits;
730
Dan Gohman1c8491e2009-04-25 17:12:48 +0000731 if (UnknownBits.isNegative()) { // Sign bit is unknown
732 Min.set(Min.getBitWidth()-1);
733 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000734 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000735}
736
737// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
738// a set of known zero and one bits, compute the maximum and minimum values that
739// could have the specified known zero and known one bits, returning them in
740// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000741static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000742 const APInt &KnownOne,
743 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000744 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
745 KnownZero.getBitWidth() == Min.getBitWidth() &&
746 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000747 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000748 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000749
750 // The minimum value is when the unknown bits are all zeros.
751 Min = KnownOne;
752 // The maximum value is when the unknown bits are all ones.
753 Max = KnownOne|UnknownBits;
754}
Chris Lattner255d8912006-02-11 09:31:47 +0000755
Chris Lattner886ab6c2009-01-31 08:15:18 +0000756/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
757/// SimplifyDemandedBits knows about. See if the instruction has any
758/// properties that allow us to simplify its operands.
759bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000760 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000761 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
762 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
763
764 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
765 KnownZero, KnownOne, 0);
766 if (V == 0) return false;
767 if (V == &Inst) return true;
768 ReplaceInstUsesWith(Inst, V);
769 return true;
770}
771
772/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
773/// specified instruction operand if possible, updating it in place. It returns
774/// true if it made any change and false otherwise.
775bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
776 APInt &KnownZero, APInt &KnownOne,
777 unsigned Depth) {
778 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
779 KnownZero, KnownOne, Depth);
780 if (NewVal == 0) return false;
781 U.set(NewVal);
782 return true;
783}
784
785
786/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
787/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000788/// that only the bits set in DemandedMask of the result of V are ever used
789/// downstream. Consequently, depending on the mask and V, it may be possible
790/// to replace V with a constant or one of its operands. In such cases, this
791/// function does the replacement and returns true. In all other cases, it
792/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000793/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000794/// to be zero in the expression. These are provided to potentially allow the
795/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
796/// the expression. KnownOne and KnownZero always follow the invariant that
797/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
798/// the bits in KnownOne and KnownZero may only be accurate for those bits set
799/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
800/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000801///
802/// This returns null if it did not change anything and it permits no
803/// simplification. This returns V itself if it did some simplification of V's
804/// operands based on the information about what bits are demanded. This returns
805/// some other non-null value if it found out that V is equal to another value
806/// in the context where the specified bits are demanded, but not for all users.
807Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
808 APInt &KnownZero, APInt &KnownOne,
809 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000810 assert(V != 0 && "Null pointer of Value???");
811 assert(Depth <= 6 && "Limit Search Depth");
812 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000813 const Type *VTy = V->getType();
814 assert((TD || !isa<PointerType>(VTy)) &&
815 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000816 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
817 (!VTy->isIntOrIntVector() ||
818 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000819 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000820 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000821 "Value *V, DemandedMask, KnownZero and KnownOne "
822 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000823 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
824 // We know all of the bits for a constant!
825 KnownOne = CI->getValue() & DemandedMask;
826 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000827 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000828 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000829 if (isa<ConstantPointerNull>(V)) {
830 // We know all of the bits for a constant!
831 KnownOne.clear();
832 KnownZero = DemandedMask;
833 return 0;
834 }
835
Chris Lattner08d2cc72009-01-31 07:26:06 +0000836 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000837 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000838 if (DemandedMask == 0) { // Not demanding any bits from V.
839 if (isa<UndefValue>(V))
840 return 0;
Owen Andersond672ecb2009-07-03 00:17:18 +0000841 return Context->getUndef(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000842 }
843
Chris Lattner4598c942009-01-31 08:24:16 +0000844 if (Depth == 6) // Limit search depth.
845 return 0;
846
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000847 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
848 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
849
Dan Gohman1c8491e2009-04-25 17:12:48 +0000850 Instruction *I = dyn_cast<Instruction>(V);
851 if (!I) {
852 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
853 return 0; // Only analyze instructions.
854 }
855
Chris Lattner4598c942009-01-31 08:24:16 +0000856 // If there are multiple uses of this value and we aren't at the root, then
857 // we can't do any simplifications of the operands, because DemandedMask
858 // only reflects the bits demanded by *one* of the users.
859 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000860 // Despite the fact that we can't simplify this instruction in all User's
861 // context, we can at least compute the knownzero/knownone bits, and we can
862 // do simplifications that apply to *just* the one user if we know that
863 // this instruction has a simpler value in that context.
864 if (I->getOpcode() == Instruction::And) {
865 // If either the LHS or the RHS are Zero, the result is zero.
866 ComputeMaskedBits(I->getOperand(1), DemandedMask,
867 RHSKnownZero, RHSKnownOne, Depth+1);
868 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
869 LHSKnownZero, LHSKnownOne, Depth+1);
870
871 // If all of the demanded bits are known 1 on one side, return the other.
872 // These bits cannot contribute to the result of the 'and' in this
873 // context.
874 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
875 (DemandedMask & ~LHSKnownZero))
876 return I->getOperand(0);
877 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
878 (DemandedMask & ~RHSKnownZero))
879 return I->getOperand(1);
880
881 // If all of the demanded bits in the inputs are known zeros, return zero.
882 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000883 return Context->getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000884
885 } else if (I->getOpcode() == Instruction::Or) {
886 // We can simplify (X|Y) -> X or Y in the user's context if we know that
887 // only bits from X or Y are demanded.
888
889 // If either the LHS or the RHS are One, the result is One.
890 ComputeMaskedBits(I->getOperand(1), DemandedMask,
891 RHSKnownZero, RHSKnownOne, Depth+1);
892 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
893 LHSKnownZero, LHSKnownOne, Depth+1);
894
895 // If all of the demanded bits are known zero on one side, return the
896 // other. These bits cannot contribute to the result of the 'or' in this
897 // context.
898 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
899 (DemandedMask & ~LHSKnownOne))
900 return I->getOperand(0);
901 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
902 (DemandedMask & ~RHSKnownOne))
903 return I->getOperand(1);
904
905 // If all of the potentially set bits on one side are known to be set on
906 // the other side, just use the 'other' side.
907 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
908 (DemandedMask & (~RHSKnownZero)))
909 return I->getOperand(0);
910 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
911 (DemandedMask & (~LHSKnownZero)))
912 return I->getOperand(1);
913 }
914
Chris Lattner4598c942009-01-31 08:24:16 +0000915 // Compute the KnownZero/KnownOne bits to simplify things downstream.
916 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
917 return 0;
918 }
919
920 // If this is the root being simplified, allow it to have multiple uses,
921 // just set the DemandedMask to all bits so that we can try to simplify the
922 // operands. This allows visitTruncInst (for example) to simplify the
923 // operand of a trunc without duplicating all the logic below.
924 if (Depth == 0 && !V->hasOneUse())
925 DemandedMask = APInt::getAllOnesValue(BitWidth);
926
Reid Spencer8cb68342007-03-12 17:25:59 +0000927 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000928 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000929 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000930 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000931 case Instruction::And:
932 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000933 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
934 RHSKnownZero, RHSKnownOne, Depth+1) ||
935 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000936 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000937 return I;
938 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
939 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000940
941 // If all of the demanded bits are known 1 on one side, return the other.
942 // These bits cannot contribute to the result of the 'and'.
943 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
944 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000945 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000946 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
947 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000948 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000949
950 // If all of the demanded bits in the inputs are known zeros, return zero.
951 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000952 return Context->getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000953
954 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000955 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000956 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000957
958 // Output known-1 bits are only known if set in both the LHS & RHS.
959 RHSKnownOne &= LHSKnownOne;
960 // Output known-0 are known to be clear if zero in either the LHS | RHS.
961 RHSKnownZero |= LHSKnownZero;
962 break;
963 case Instruction::Or:
964 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000965 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
966 RHSKnownZero, RHSKnownOne, Depth+1) ||
967 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000968 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000969 return I;
970 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
971 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000972
973 // If all of the demanded bits are known zero on one side, return the other.
974 // These bits cannot contribute to the result of the 'or'.
975 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
976 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000977 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000978 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
979 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000980 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000981
982 // If all of the potentially set bits on one side are known to be set on
983 // the other side, just use the 'other' side.
984 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
985 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000986 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000987 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
988 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000989 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000990
991 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000992 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000993 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000994
995 // Output known-0 bits are only known if clear in both the LHS & RHS.
996 RHSKnownZero &= LHSKnownZero;
997 // Output known-1 are known to be set if set in either the LHS | RHS.
998 RHSKnownOne |= LHSKnownOne;
999 break;
1000 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001001 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1002 RHSKnownZero, RHSKnownOne, Depth+1) ||
1003 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001004 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001005 return I;
1006 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1007 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001008
1009 // If all of the demanded bits are known zero on one side, return the other.
1010 // These bits cannot contribute to the result of the 'xor'.
1011 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001012 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001013 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001014 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001015
1016 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1017 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1018 (RHSKnownOne & LHSKnownOne);
1019 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1020 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1021 (RHSKnownOne & LHSKnownZero);
1022
1023 // If all of the demanded bits are known to be zero on one side or the
1024 // other, turn this into an *inclusive* or.
1025 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1026 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1027 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001028 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001029 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001030 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001031 }
1032
1033 // If all of the demanded bits on one side are known, and all of the set
1034 // bits on that side are also known to be set on the other side, turn this
1035 // into an AND, as we know the bits will be cleared.
1036 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1037 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1038 // all known
1039 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001040 Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001041 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001042 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001043 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001044 }
1045 }
1046
1047 // If the RHS is a constant, see if we can simplify it.
1048 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Owen Andersond672ecb2009-07-03 00:17:18 +00001049 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001050 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001051
1052 RHSKnownZero = KnownZeroOut;
1053 RHSKnownOne = KnownOneOut;
1054 break;
1055 }
1056 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001057 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1058 RHSKnownZero, RHSKnownOne, Depth+1) ||
1059 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001060 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001061 return I;
1062 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1063 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001064
1065 // If the operands are constants, see if we can simplify them.
Owen Andersond672ecb2009-07-03 00:17:18 +00001066 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1067 ShrinkDemandedConstant(I, 2, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001068 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001069
1070 // Only known if known in both the LHS and RHS.
1071 RHSKnownOne &= LHSKnownOne;
1072 RHSKnownZero &= LHSKnownZero;
1073 break;
1074 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001075 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001076 DemandedMask.zext(truncBf);
1077 RHSKnownZero.zext(truncBf);
1078 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001079 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001080 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001081 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001082 DemandedMask.trunc(BitWidth);
1083 RHSKnownZero.trunc(BitWidth);
1084 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001085 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001086 break;
1087 }
1088 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001089 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001090 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001091
1092 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1093 if (const VectorType *SrcVTy =
1094 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1095 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1096 // Don't touch a bitcast between vectors of different element counts.
1097 return false;
1098 } else
1099 // Don't touch a scalar-to-vector bitcast.
1100 return false;
1101 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1102 // Don't touch a vector-to-scalar bitcast.
1103 return false;
1104
Chris Lattner886ab6c2009-01-31 08:15:18 +00001105 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001106 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001107 return I;
1108 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001109 break;
1110 case Instruction::ZExt: {
1111 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001112 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001113
Zhou Shengd48653a2007-03-29 04:45:55 +00001114 DemandedMask.trunc(SrcBitWidth);
1115 RHSKnownZero.trunc(SrcBitWidth);
1116 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001117 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001118 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001119 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001120 DemandedMask.zext(BitWidth);
1121 RHSKnownZero.zext(BitWidth);
1122 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001123 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001124 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001125 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001126 break;
1127 }
1128 case Instruction::SExt: {
1129 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001130 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001131
Reid Spencer8cb68342007-03-12 17:25:59 +00001132 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001133 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001134
Zhou Sheng01542f32007-03-29 02:26:30 +00001135 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001136 // If any of the sign extended bits are demanded, we know that the sign
1137 // bit is demanded.
1138 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001139 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001140
Zhou Shengd48653a2007-03-29 04:45:55 +00001141 InputDemandedBits.trunc(SrcBitWidth);
1142 RHSKnownZero.trunc(SrcBitWidth);
1143 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001144 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001145 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001146 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001147 InputDemandedBits.zext(BitWidth);
1148 RHSKnownZero.zext(BitWidth);
1149 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001150 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001151
1152 // If the sign bit of the input is known set or clear, then we know the
1153 // top bits of the result.
1154
1155 // If the input sign bit is known zero, or if the NewBits are not demanded
1156 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001157 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001158 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001159 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1160 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001161 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001162 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001163 }
1164 break;
1165 }
1166 case Instruction::Add: {
1167 // Figure out what the input bits are. If the top bits of the and result
1168 // are not demanded, then the add doesn't demand them from its input
1169 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001170 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001171
1172 // If there is a constant on the RHS, there are a variety of xformations
1173 // we can do.
1174 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1175 // If null, this should be simplified elsewhere. Some of the xforms here
1176 // won't work if the RHS is zero.
1177 if (RHS->isZero())
1178 break;
1179
1180 // If the top bit of the output is demanded, demand everything from the
1181 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001182 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001183
1184 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001185 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001186 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001187 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001188
1189 // If the RHS of the add has bits set that can't affect the input, reduce
1190 // the constant.
Owen Andersond672ecb2009-07-03 00:17:18 +00001191 if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001192 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001193
1194 // Avoid excess work.
1195 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1196 break;
1197
1198 // Turn it into OR if input bits are zero.
1199 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1200 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001201 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001202 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001203 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001204 }
1205
1206 // We can say something about the output known-zero and known-one bits,
1207 // depending on potential carries from the input constant and the
1208 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1209 // bits set and the RHS constant is 0x01001, then we know we have a known
1210 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1211
1212 // To compute this, we first compute the potential carry bits. These are
1213 // the bits which may be modified. I'm not aware of a better way to do
1214 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001215 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001216 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001217
1218 // Now that we know which bits have carries, compute the known-1/0 sets.
1219
1220 // Bits are known one if they are known zero in one operand and one in the
1221 // other, and there is no input carry.
1222 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1223 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1224
1225 // Bits are known zero if they are known zero in both operands and there
1226 // is no input carry.
1227 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1228 } else {
1229 // If the high-bits of this ADD are not demanded, then it does not demand
1230 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001231 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001232 // Right fill the mask of bits for this ADD to demand the most
1233 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001234 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001235 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1236 LHSKnownZero, LHSKnownOne, Depth+1) ||
1237 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001238 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001239 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001240 }
1241 }
1242 break;
1243 }
1244 case Instruction::Sub:
1245 // If the high-bits of this SUB are not demanded, then it does not demand
1246 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001247 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001248 // Right fill the mask of bits for this SUB to demand the most
1249 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001250 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001251 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001252 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1253 LHSKnownZero, LHSKnownOne, Depth+1) ||
1254 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001255 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001256 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001257 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001258 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1259 // the known zeros and ones.
1260 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001261 break;
1262 case Instruction::Shl:
1263 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001264 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001265 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001266 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001267 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001268 return I;
1269 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001270 RHSKnownZero <<= ShiftAmt;
1271 RHSKnownOne <<= ShiftAmt;
1272 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001273 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001274 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001275 }
1276 break;
1277 case Instruction::LShr:
1278 // For a logical shift right
1279 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001280 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001281
Reid Spencer8cb68342007-03-12 17:25:59 +00001282 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001283 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001284 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001285 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001286 return I;
1287 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001288 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1289 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001290 if (ShiftAmt) {
1291 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001292 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001293 RHSKnownZero |= HighBits; // high bits known zero.
1294 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001295 }
1296 break;
1297 case Instruction::AShr:
1298 // If this is an arithmetic shift right and only the low-bit is set, we can
1299 // always convert this into a logical shr, even if the shift amount is
1300 // variable. The low bit of the shift cannot be an input sign bit unless
1301 // the shift amount is >= the size of the datatype, which is undefined.
1302 if (DemandedMask == 1) {
1303 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001304 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001305 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001306 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001307 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001308
1309 // If the sign bit is the only bit demanded by this ashr, then there is no
1310 // need to do it, the shift doesn't change the high bit.
1311 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001312 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001313
1314 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001315 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001316
Reid Spencer8cb68342007-03-12 17:25:59 +00001317 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001318 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001319 // If any of the "high bits" are demanded, we should set the sign bit as
1320 // demanded.
1321 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1322 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001323 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001324 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001325 return I;
1326 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001327 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001328 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001329 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1330 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1331
1332 // Handle the sign bits.
1333 APInt SignBit(APInt::getSignBit(BitWidth));
1334 // Adjust to where it is now in the mask.
1335 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1336
1337 // If the input sign bit is known to be zero, or if none of the top bits
1338 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001339 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001340 (HighBits & ~DemandedMask) == HighBits) {
1341 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001342 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001343 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001344 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001345 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1346 RHSKnownOne |= HighBits;
1347 }
1348 }
1349 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001350 case Instruction::SRem:
1351 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001352 APInt RA = Rem->getValue().abs();
1353 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001354 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001355 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001356
Nick Lewycky8e394322008-11-02 02:41:50 +00001357 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001358 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001359 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001360 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001361 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001362
1363 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1364 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001365
1366 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001367
Chris Lattner886ab6c2009-01-31 08:15:18 +00001368 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001369 }
1370 }
1371 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001372 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001373 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1374 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001375 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1376 KnownZero2, KnownOne2, Depth+1) ||
1377 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001378 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001379 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001380
Chris Lattner455e9ab2009-01-21 18:09:24 +00001381 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001382 Leaders = std::max(Leaders,
1383 KnownZero2.countLeadingOnes());
1384 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001385 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001386 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001387 case Instruction::Call:
1388 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1389 switch (II->getIntrinsicID()) {
1390 default: break;
1391 case Intrinsic::bswap: {
1392 // If the only bits demanded come from one byte of the bswap result,
1393 // just shift the input byte into position to eliminate the bswap.
1394 unsigned NLZ = DemandedMask.countLeadingZeros();
1395 unsigned NTZ = DemandedMask.countTrailingZeros();
1396
1397 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1398 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1399 // have 14 leading zeros, round to 8.
1400 NLZ &= ~7;
1401 NTZ &= ~7;
1402 // If we need exactly one byte, we can do this transformation.
1403 if (BitWidth-NLZ-NTZ == 8) {
1404 unsigned ResultBit = NTZ;
1405 unsigned InputBit = BitWidth-NTZ-8;
1406
1407 // Replace this with either a left or right shift to get the byte into
1408 // the right place.
1409 Instruction *NewVal;
1410 if (InputBit > ResultBit)
1411 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00001412 Context->getConstantInt(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001413 else
1414 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00001415 Context->getConstantInt(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001416 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001417 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001418 }
1419
1420 // TODO: Could compute known zero/one bits based on the input.
1421 break;
1422 }
1423 }
1424 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001425 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001426 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001427 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001428
1429 // If the client is only demanding bits that we know, return the known
1430 // constant.
Dan Gohman1c8491e2009-04-25 17:12:48 +00001431 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001432 Constant *C = Context->getConstantInt(RHSKnownOne);
Dan Gohman1c8491e2009-04-25 17:12:48 +00001433 if (isa<PointerType>(V->getType()))
Owen Andersond672ecb2009-07-03 00:17:18 +00001434 C = Context->getConstantExprIntToPtr(C, V->getType());
Dan Gohman1c8491e2009-04-25 17:12:48 +00001435 return C;
1436 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001437 return false;
1438}
1439
Chris Lattner867b99f2006-10-05 06:55:50 +00001440
Mon P Wangaeb06d22008-11-10 04:46:22 +00001441/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001442/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001443/// actually used by the caller. This method analyzes which elements of the
1444/// operand are undef and returns that information in UndefElts.
1445///
1446/// If the information about demanded elements can be used to simplify the
1447/// operation, the operation is simplified, then the resultant value is
1448/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001449Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1450 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001451 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001452 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001453 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001454 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001455
1456 if (isa<UndefValue>(V)) {
1457 // If the entire vector is undefined, just return this info.
1458 UndefElts = EltMask;
1459 return 0;
1460 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1461 UndefElts = EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001462 return Context->getUndef(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001463 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001464
Chris Lattner867b99f2006-10-05 06:55:50 +00001465 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001466 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1467 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001468 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001469
1470 std::vector<Constant*> Elts;
1471 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001472 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001473 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001474 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001475 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1476 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001477 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001478 } else { // Otherwise, defined.
1479 Elts.push_back(CP->getOperand(i));
1480 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001481
Chris Lattner867b99f2006-10-05 06:55:50 +00001482 // If we changed the constant, return it.
Owen Andersond672ecb2009-07-03 00:17:18 +00001483 Constant *NewCP = Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001484 return NewCP != CP ? NewCP : 0;
1485 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001486 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001487 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001488
1489 // Check if this is identity. If so, return 0 since we are not simplifying
1490 // anything.
1491 if (DemandedElts == ((1ULL << VWidth) -1))
1492 return 0;
1493
Reid Spencer9d6565a2007-02-15 02:26:10 +00001494 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001495 Constant *Zero = Context->getNullValue(EltTy);
1496 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001497 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001498 for (unsigned i = 0; i != VWidth; ++i) {
1499 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1500 Elts.push_back(Elt);
1501 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001502 UndefElts = DemandedElts ^ EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001503 return Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001504 }
1505
Dan Gohman488fbfc2008-09-09 18:11:14 +00001506 // Limit search depth.
1507 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001508 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001509
1510 // If multiple users are using the root value, procede with
1511 // simplification conservatively assuming that all elements
1512 // are needed.
1513 if (!V->hasOneUse()) {
1514 // Quit if we find multiple users of a non-root value though.
1515 // They'll be handled when it's their turn to be visited by
1516 // the main instcombine process.
1517 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001518 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001519 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001520
1521 // Conservatively assume that all elements are needed.
1522 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001523 }
1524
1525 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001526 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001527
1528 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001529 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001530 Value *TmpV;
1531 switch (I->getOpcode()) {
1532 default: break;
1533
1534 case Instruction::InsertElement: {
1535 // If this is a variable index, we don't know which element it overwrites.
1536 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001537 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001538 if (Idx == 0) {
1539 // Note that we can't propagate undef elt info, because we don't know
1540 // which elt is getting updated.
1541 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1542 UndefElts2, Depth+1);
1543 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1544 break;
1545 }
1546
1547 // If this is inserting an element that isn't demanded, remove this
1548 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001549 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001550 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001551 return AddSoonDeadInstToWorklist(*I, 0);
1552
1553 // Otherwise, the element inserted overwrites whatever was there, so the
1554 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001555 APInt DemandedElts2 = DemandedElts;
1556 DemandedElts2.clear(IdxNo);
1557 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001558 UndefElts, Depth+1);
1559 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1560
1561 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001562 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001563 break;
1564 }
1565 case Instruction::ShuffleVector: {
1566 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001567 uint64_t LHSVWidth =
1568 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001569 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001570 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001571 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001572 unsigned MaskVal = Shuffle->getMaskValue(i);
1573 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001574 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001575 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001576 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001577 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001578 else
Evan Cheng388df622009-02-03 10:05:09 +00001579 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001580 }
1581 }
1582 }
1583
Nate Begeman7b254672009-02-11 22:36:25 +00001584 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001585 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001586 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001587 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1588
Nate Begeman7b254672009-02-11 22:36:25 +00001589 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001590 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1591 UndefElts3, Depth+1);
1592 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1593
1594 bool NewUndefElts = false;
1595 for (unsigned i = 0; i < VWidth; i++) {
1596 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001597 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001598 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001599 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001600 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001601 NewUndefElts = true;
1602 UndefElts.set(i);
1603 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001604 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001605 if (UndefElts3[MaskVal - LHSVWidth]) {
1606 NewUndefElts = true;
1607 UndefElts.set(i);
1608 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001609 }
1610 }
1611
1612 if (NewUndefElts) {
1613 // Add additional discovered undefs.
1614 std::vector<Constant*> Elts;
1615 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001616 if (UndefElts[i])
Owen Andersond672ecb2009-07-03 00:17:18 +00001617 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001618 else
Owen Andersond672ecb2009-07-03 00:17:18 +00001619 Elts.push_back(Context->getConstantInt(Type::Int32Ty,
Dan Gohman488fbfc2008-09-09 18:11:14 +00001620 Shuffle->getMaskValue(i)));
1621 }
Owen Andersond672ecb2009-07-03 00:17:18 +00001622 I->setOperand(2, Context->getConstantVector(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001623 MadeChange = true;
1624 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001625 break;
1626 }
Chris Lattner69878332007-04-14 22:29:23 +00001627 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001628 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001629 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1630 if (!VTy) break;
1631 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001632 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001633 unsigned Ratio;
1634
1635 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001636 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001637 // elements as are demanded of us.
1638 Ratio = 1;
1639 InputDemandedElts = DemandedElts;
1640 } else if (VWidth > InVWidth) {
1641 // Untested so far.
1642 break;
1643
1644 // If there are more elements in the result than there are in the source,
1645 // then an input element is live if any of the corresponding output
1646 // elements are live.
1647 Ratio = VWidth/InVWidth;
1648 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001649 if (DemandedElts[OutIdx])
1650 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001651 }
1652 } else {
1653 // Untested so far.
1654 break;
1655
1656 // If there are more elements in the source than there are in the result,
1657 // then an input element is live if the corresponding output element is
1658 // live.
1659 Ratio = InVWidth/VWidth;
1660 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001661 if (DemandedElts[InIdx/Ratio])
1662 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001663 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001664
Chris Lattner69878332007-04-14 22:29:23 +00001665 // div/rem demand all inputs, because they don't want divide by zero.
1666 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1667 UndefElts2, Depth+1);
1668 if (TmpV) {
1669 I->setOperand(0, TmpV);
1670 MadeChange = true;
1671 }
1672
1673 UndefElts = UndefElts2;
1674 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001675 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001676 // If there are more elements in the result than there are in the source,
1677 // then an output element is undef if the corresponding input element is
1678 // undef.
1679 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001680 if (UndefElts2[OutIdx/Ratio])
1681 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001682 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001683 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001684 // If there are more elements in the source than there are in the result,
1685 // then a result element is undef if all of the corresponding input
1686 // elements are undef.
1687 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1688 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001689 if (!UndefElts2[InIdx]) // Not undef?
1690 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001691 }
1692 break;
1693 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001694 case Instruction::And:
1695 case Instruction::Or:
1696 case Instruction::Xor:
1697 case Instruction::Add:
1698 case Instruction::Sub:
1699 case Instruction::Mul:
1700 // div/rem demand all inputs, because they don't want divide by zero.
1701 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1702 UndefElts, Depth+1);
1703 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1704 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1705 UndefElts2, Depth+1);
1706 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1707
1708 // Output elements are undefined if both are undefined. Consider things
1709 // like undef&0. The result is known zero, not undef.
1710 UndefElts &= UndefElts2;
1711 break;
1712
1713 case Instruction::Call: {
1714 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1715 if (!II) break;
1716 switch (II->getIntrinsicID()) {
1717 default: break;
1718
1719 // Binary vector operations that work column-wise. A dest element is a
1720 // function of the corresponding input elements from the two inputs.
1721 case Intrinsic::x86_sse_sub_ss:
1722 case Intrinsic::x86_sse_mul_ss:
1723 case Intrinsic::x86_sse_min_ss:
1724 case Intrinsic::x86_sse_max_ss:
1725 case Intrinsic::x86_sse2_sub_sd:
1726 case Intrinsic::x86_sse2_mul_sd:
1727 case Intrinsic::x86_sse2_min_sd:
1728 case Intrinsic::x86_sse2_max_sd:
1729 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1730 UndefElts, Depth+1);
1731 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1732 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1733 UndefElts2, Depth+1);
1734 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1735
1736 // If only the low elt is demanded and this is a scalarizable intrinsic,
1737 // scalarize it now.
1738 if (DemandedElts == 1) {
1739 switch (II->getIntrinsicID()) {
1740 default: break;
1741 case Intrinsic::x86_sse_sub_ss:
1742 case Intrinsic::x86_sse_mul_ss:
1743 case Intrinsic::x86_sse2_sub_sd:
1744 case Intrinsic::x86_sse2_mul_sd:
1745 // TODO: Lower MIN/MAX/ABS/etc
1746 Value *LHS = II->getOperand(1);
1747 Value *RHS = II->getOperand(2);
1748 // Extract the element as scalars.
Owen Anderson9adc0ab2009-07-14 23:09:55 +00001749 LHS = InsertNewInstBefore(new ExtractElementInst(LHS,
1750 Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1751 RHS = InsertNewInstBefore(new ExtractElementInst(RHS,
1752 Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001753
1754 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001755 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001756 case Intrinsic::x86_sse_sub_ss:
1757 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001758 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001759 II->getName()), *II);
1760 break;
1761 case Intrinsic::x86_sse_mul_ss:
1762 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001763 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001764 II->getName()), *II);
1765 break;
1766 }
1767
1768 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001769 InsertElementInst::Create(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00001770 Context->getUndef(II->getType()), TmpV,
1771 Context->getConstantInt(Type::Int32Ty, 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001772 InsertNewInstBefore(New, *II);
1773 AddSoonDeadInstToWorklist(*II, 0);
1774 return New;
1775 }
1776 }
1777
1778 // Output elements are undefined if both are undefined. Consider things
1779 // like undef&0. The result is known zero, not undef.
1780 UndefElts &= UndefElts2;
1781 break;
1782 }
1783 break;
1784 }
1785 }
1786 return MadeChange ? I : 0;
1787}
1788
Dan Gohman45b4e482008-05-19 22:14:15 +00001789
Chris Lattner564a7272003-08-13 19:01:45 +00001790/// AssociativeOpt - Perform an optimization on an associative operator. This
1791/// function is designed to check a chain of associative operators for a
1792/// potential to apply a certain optimization. Since the optimization may be
1793/// applicable if the expression was reassociated, this checks the chain, then
1794/// reassociates the expression as necessary to expose the optimization
1795/// opportunity. This makes use of a special Functor, which must define
1796/// 'shouldApply' and 'apply' methods.
1797///
1798template<typename Functor>
Owen Andersond672ecb2009-07-03 00:17:18 +00001799static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001800 LLVMContext *Context) {
Chris Lattner564a7272003-08-13 19:01:45 +00001801 unsigned Opcode = Root.getOpcode();
1802 Value *LHS = Root.getOperand(0);
1803
1804 // Quick check, see if the immediate LHS matches...
1805 if (F.shouldApply(LHS))
1806 return F.apply(Root);
1807
1808 // Otherwise, if the LHS is not of the same opcode as the root, return.
1809 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001810 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001811 // Should we apply this transform to the RHS?
1812 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1813
1814 // If not to the RHS, check to see if we should apply to the LHS...
1815 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1816 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1817 ShouldApply = true;
1818 }
1819
1820 // If the functor wants to apply the optimization to the RHS of LHSI,
1821 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1822 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001823 // Now all of the instructions are in the current basic block, go ahead
1824 // and perform the reassociation.
1825 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1826
1827 // First move the selected RHS to the LHS of the root...
1828 Root.setOperand(0, LHSI->getOperand(1));
1829
1830 // Make what used to be the LHS of the root be the user of the root...
1831 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001832 if (&Root == TmpLHSI) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001833 Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001834 return 0;
1835 }
Chris Lattner65725312004-04-16 18:08:07 +00001836 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001837 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001838 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001839 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001840 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001841
1842 // Now propagate the ExtraOperand down the chain of instructions until we
1843 // get to LHSI.
1844 while (TmpLHSI != LHSI) {
1845 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001846 // Move the instruction to immediately before the chain we are
1847 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001848 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001849 ARI = NextLHSI;
1850
Chris Lattner564a7272003-08-13 19:01:45 +00001851 Value *NextOp = NextLHSI->getOperand(1);
1852 NextLHSI->setOperand(1, ExtraOperand);
1853 TmpLHSI = NextLHSI;
1854 ExtraOperand = NextOp;
1855 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001856
Chris Lattner564a7272003-08-13 19:01:45 +00001857 // Now that the instructions are reassociated, have the functor perform
1858 // the transformation...
1859 return F.apply(Root);
1860 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001861
Chris Lattner564a7272003-08-13 19:01:45 +00001862 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1863 }
1864 return 0;
1865}
1866
Dan Gohman844731a2008-05-13 00:00:25 +00001867namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001868
Nick Lewycky02d639f2008-05-23 04:34:58 +00001869// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001870struct AddRHS {
1871 Value *RHS;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001872 LLVMContext *Context;
1873 AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001874 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1875 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001876 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00001877 Context->getConstantInt(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001878 }
1879};
1880
1881// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1882// iff C1&C2 == 0
1883struct AddMaskingAnd {
1884 Constant *C2;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001885 LLVMContext *Context;
1886 AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001887 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001888 ConstantInt *C1;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00001889 return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
Owen Andersond672ecb2009-07-03 00:17:18 +00001890 Context->getConstantExprAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001891 }
1892 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001893 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001894 }
1895};
1896
Dan Gohman844731a2008-05-13 00:00:25 +00001897}
1898
Chris Lattner6e7ba452005-01-01 16:22:27 +00001899static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001900 InstCombiner *IC) {
Owen Anderson07cf79e2009-07-06 23:00:19 +00001901 LLVMContext *Context = IC->getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00001902
Reid Spencer3da59db2006-11-27 01:05:10 +00001903 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001904 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001905 }
1906
Chris Lattner2eefe512004-04-09 19:05:30 +00001907 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001908 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1909 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001910
Chris Lattner2eefe512004-04-09 19:05:30 +00001911 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1912 if (ConstIsRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00001913 return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1914 return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001915 }
1916
1917 Value *Op0 = SO, *Op1 = ConstOperand;
1918 if (!ConstIsRHS)
1919 std::swap(Op0, Op1);
1920 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001921 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001922 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001923 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00001924 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1925 Op0, Op1, SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001926 else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001927 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001928 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001929 return IC->InsertNewInstBefore(New, I);
1930}
1931
1932// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1933// constant as the other operand, try to fold the binary operator into the
1934// select arguments. This also works for Cast instructions, which obviously do
1935// not have a second operand.
1936static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1937 InstCombiner *IC) {
1938 // Don't modify shared select instructions
1939 if (!SI->hasOneUse()) return 0;
1940 Value *TV = SI->getOperand(1);
1941 Value *FV = SI->getOperand(2);
1942
1943 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001944 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001945 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001946
Chris Lattner6e7ba452005-01-01 16:22:27 +00001947 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1948 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1949
Gabor Greif051a9502008-04-06 20:25:17 +00001950 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1951 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001952 }
1953 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001954}
1955
Chris Lattner4e998b22004-09-29 05:07:12 +00001956
1957/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1958/// node as operand #0, see if we can fold the instruction into the PHI (which
1959/// is only possible if all operands to the PHI are constants).
1960Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1961 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001962 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001963 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001964
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001965 // Check to see if all of the operands of the PHI are constants. If there is
1966 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001967 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001968 BasicBlock *NonConstBB = 0;
1969 for (unsigned i = 0; i != NumPHIValues; ++i)
1970 if (!isa<Constant>(PN->getIncomingValue(i))) {
1971 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001972 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001973 NonConstBB = PN->getIncomingBlock(i);
1974
1975 // If the incoming non-constant value is in I's block, we have an infinite
1976 // loop.
1977 if (NonConstBB == I.getParent())
1978 return 0;
1979 }
1980
1981 // If there is exactly one non-constant value, we can insert a copy of the
1982 // operation in that block. However, if this is a critical edge, we would be
1983 // inserting the computation one some other paths (e.g. inside a loop). Only
1984 // do this if the pred block is unconditionally branching into the phi block.
1985 if (NonConstBB) {
1986 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1987 if (!BI || !BI->isUnconditional()) return 0;
1988 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001989
1990 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001991 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001992 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001993 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001994 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001995
1996 // Next, add all of the operands to the PHI.
1997 if (I.getNumOperands() == 2) {
1998 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001999 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002000 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002001 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002002 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersond672ecb2009-07-03 00:17:18 +00002003 InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002004 else
Owen Andersond672ecb2009-07-03 00:17:18 +00002005 InV = Context->getConstantExpr(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002006 } else {
2007 assert(PN->getIncomingBlock(i) == NonConstBB);
2008 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002009 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002010 PN->getIncomingValue(i), C, "phitmp",
2011 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002012 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00002013 InV = CmpInst::Create(*Context, CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002014 CI->getPredicate(),
2015 PN->getIncomingValue(i), C, "phitmp",
2016 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002017 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002018 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002019
Chris Lattnerdbab3862007-03-02 21:28:56 +00002020 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002021 }
2022 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002023 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002024 } else {
2025 CastInst *CI = cast<CastInst>(&I);
2026 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002027 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002028 Value *InV;
2029 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002030 InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002031 } else {
2032 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002033 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002034 I.getType(), "phitmp",
2035 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002036 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002037 }
2038 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002039 }
2040 }
2041 return ReplaceInstUsesWith(I, NewPN);
2042}
2043
Chris Lattner2454a2e2008-01-29 06:52:45 +00002044
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002045/// WillNotOverflowSignedAdd - Return true if we can prove that:
2046/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2047/// This basically requires proving that the add in the original type would not
2048/// overflow to change the sign bit or have a carry out.
2049bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2050 // There are different heuristics we can use for this. Here are some simple
2051 // ones.
2052
2053 // Add has the property that adding any two 2's complement numbers can only
2054 // have one carry bit which can change a sign. As such, if LHS and RHS each
2055 // have at least two sign bits, we know that the addition of the two values will
2056 // sign extend fine.
2057 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2058 return true;
2059
2060
2061 // If one of the operands only has one non-zero bit, and if the other operand
2062 // has a known-zero bit in a more significant place than it (not including the
2063 // sign bit) the ripple may go up to and fill the zero, but won't change the
2064 // sign. For example, (X & ~4) + 1.
2065
2066 // TODO: Implement.
2067
2068 return false;
2069}
2070
Chris Lattner2454a2e2008-01-29 06:52:45 +00002071
Chris Lattner7e708292002-06-25 16:13:24 +00002072Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002073 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002074 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002075
Chris Lattner66331a42004-04-10 22:01:55 +00002076 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002077 // X + undef -> undef
2078 if (isa<UndefValue>(RHS))
2079 return ReplaceInstUsesWith(I, RHS);
2080
Chris Lattner66331a42004-04-10 22:01:55 +00002081 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002082 if (RHSC->isNullValue())
2083 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002084
Chris Lattner66331a42004-04-10 22:01:55 +00002085 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002086 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002087 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002088 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002089 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002090 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002091
2092 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2093 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002094 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002095 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002096
Eli Friedman709b33d2009-07-13 22:27:52 +00002097 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002098 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Eli Friedman709b33d2009-07-13 22:27:52 +00002099 if (ZI->getSrcTy() == Type::Int1Ty)
2100 return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002101 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002102
2103 if (isa<PHINode>(LHS))
2104 if (Instruction *NV = FoldOpIntoPhi(I))
2105 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002106
Chris Lattner4f637d42006-01-06 17:59:59 +00002107 ConstantInt *XorRHS = 0;
2108 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002109 if (isa<ConstantInt>(RHSC) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002110 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002111 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002112 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002113
Zhou Sheng4351c642007-04-02 08:20:41 +00002114 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002115 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2116 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002117 do {
2118 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002119 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2120 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002121 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2122 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002123 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002124 if (!MaskedValueIsZero(XorLHS,
2125 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002126 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002127 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002128 }
2129 }
2130 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002131 C0080Val = APIntOps::lshr(C0080Val, Size);
2132 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2133 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002134
Reid Spencer35c38852007-03-28 01:36:16 +00002135 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002136 // with funny bit widths then this switch statement should be removed. It
2137 // is just here to get the size of the "middle" type back up to something
2138 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002139 const Type *MiddleType = 0;
2140 switch (Size) {
2141 default: break;
2142 case 32: MiddleType = Type::Int32Ty; break;
2143 case 16: MiddleType = Type::Int16Ty; break;
2144 case 8: MiddleType = Type::Int8Ty; break;
2145 }
2146 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002147 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002148 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002149 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002150 }
2151 }
Chris Lattner66331a42004-04-10 22:01:55 +00002152 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002153
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002154 if (I.getType() == Type::Int1Ty)
2155 return BinaryOperator::CreateXor(LHS, RHS);
2156
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002157 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002158 if (I.getType()->isInteger()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002159 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2160 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002161
2162 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2163 if (RHSI->getOpcode() == Instruction::Sub)
2164 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2165 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2166 }
2167 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2168 if (LHSI->getOpcode() == Instruction::Sub)
2169 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2170 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2171 }
Robert Bocchino71698282004-07-27 21:02:21 +00002172 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002173
Chris Lattner5c4afb92002-05-08 22:46:53 +00002174 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002175 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002176 if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002177 if (LHS->getType()->isIntOrIntVector()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002178 if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002179 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002180 InsertNewInstBefore(NewAdd, I);
Owen Anderson0a5372e2009-07-13 04:09:18 +00002181 return BinaryOperator::CreateNeg(*Context, NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002182 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002183 }
2184
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002185 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002186 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002187
2188 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002189 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002190 if (Value *V = dyn_castNegVal(RHS, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002191 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002192
Misha Brukmanfd939082005-04-21 23:48:37 +00002193
Chris Lattner50af16a2004-11-13 19:50:12 +00002194 ConstantInt *C2;
Owen Andersond672ecb2009-07-03 00:17:18 +00002195 if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002196 if (X == RHS) // X*C + X --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002197 return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002198
2199 // X*C1 + X*C2 --> X * (C1+C2)
2200 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002201 if (X == dyn_castFoldableMul(RHS, C1, Context))
2202 return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002203 }
2204
2205 // X + X*C --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002206 if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2207 return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002208
Chris Lattnere617c9e2007-01-05 02:17:46 +00002209 // X + ~X --> -1 since ~X = -X-1
Owen Andersond672ecb2009-07-03 00:17:18 +00002210 if (dyn_castNotVal(LHS, Context) == RHS ||
2211 dyn_castNotVal(RHS, Context) == LHS)
2212 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002213
Chris Lattnerad3448c2003-02-18 19:57:07 +00002214
Chris Lattner564a7272003-08-13 19:01:45 +00002215 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002216 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002217 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002218 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002219
2220 // A+B --> A|B iff A and B have no bits set in common.
2221 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2222 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2223 APInt LHSKnownOne(IT->getBitWidth(), 0);
2224 APInt LHSKnownZero(IT->getBitWidth(), 0);
2225 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2226 if (LHSKnownZero != 0) {
2227 APInt RHSKnownOne(IT->getBitWidth(), 0);
2228 APInt RHSKnownZero(IT->getBitWidth(), 0);
2229 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2230
2231 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002232 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002233 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002234 }
2235 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002236
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002237 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002238 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002239 Value *W, *X, *Y, *Z;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002240 if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2241 match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002242 if (W != Y) {
2243 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002244 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002245 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002246 std::swap(W, X);
2247 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002248 std::swap(Y, Z);
2249 std::swap(W, X);
2250 }
2251 }
2252
2253 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002254 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002255 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002256 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002257 }
2258 }
2259 }
2260
Chris Lattner6b032052003-10-02 15:11:26 +00002261 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002262 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002263 if (match(LHS, m_Not(m_Value(X)), *Context)) // ~X + C --> (C-1) - X
Owen Andersond672ecb2009-07-03 00:17:18 +00002264 return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002265
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002266 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002267 if (LHS->hasOneUse() &&
2268 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002269 Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002270 if (Anded == CRHS) {
2271 // See if all bits from the first bit set in the Add RHS up are included
2272 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002273 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002274
2275 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002276 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002277
2278 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002279 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002280
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002281 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2282 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002283 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002284 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002285 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002286 }
2287 }
2288 }
2289
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002290 // Try to fold constant add into select arguments.
2291 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002292 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002293 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002294 }
2295
Reid Spencer1628cec2006-10-26 06:15:43 +00002296 // add (cast *A to intptrtype) B ->
Dan Gohmana119de82009-06-14 23:30:43 +00002297 // cast (GEP (cast *A to i8*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002298 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002299 CastInst *CI = dyn_cast<CastInst>(LHS);
2300 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002301 if (!CI) {
2302 CI = dyn_cast<CastInst>(RHS);
2303 Other = LHS;
2304 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002305 if (CI && CI->getType()->isSized() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00002306 (CI->getType()->getScalarSizeInBits() ==
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002307 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002308 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002309 unsigned AS =
2310 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002311 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002312 Context->getPointerType(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002313 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002314 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002315 }
2316 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002317
Chris Lattner42790482007-12-20 01:56:58 +00002318 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002319 {
2320 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002321 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002322 if (!SI) {
2323 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002324 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002325 }
Chris Lattner42790482007-12-20 01:56:58 +00002326 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002327 Value *TV = SI->getTrueValue();
2328 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002329 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002330
2331 // Can we fold the add into the argument of the select?
2332 // We check both true and false select arguments for a matching subtract.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002333 if (match(FV, m_Zero(), *Context) &&
2334 match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002335 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002336 return SelectInst::Create(SI->getCondition(), N, A);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002337 if (match(TV, m_Zero(), *Context) &&
2338 match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002339 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002340 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002341 }
2342 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002343
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002344 // Check for (add (sext x), y), see if we can merge this into an
2345 // integer add followed by a sext.
2346 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2347 // (add (sext x), cst) --> (sext (add x, cst'))
2348 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2349 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002350 Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002351 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002352 Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002353 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2354 // Insert the new, smaller add.
2355 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2356 CI, "addconv");
2357 InsertNewInstBefore(NewAdd, I);
2358 return new SExtInst(NewAdd, I.getType());
2359 }
2360 }
2361
2362 // (add (sext x), (sext y)) --> (sext (add int x, y))
2363 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2364 // Only do this if x/y have the same type, if at last one of them has a
2365 // single use (so we don't increase the number of sexts), and if the
2366 // integer add will not overflow.
2367 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2368 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2369 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2370 RHSConv->getOperand(0))) {
2371 // Insert the new integer add.
2372 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2373 RHSConv->getOperand(0),
2374 "addconv");
2375 InsertNewInstBefore(NewAdd, I);
2376 return new SExtInst(NewAdd, I.getType());
2377 }
2378 }
2379 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002380
2381 return Changed ? &I : 0;
2382}
2383
2384Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2385 bool Changed = SimplifyCommutative(I);
2386 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2387
2388 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2389 // X + 0 --> X
2390 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002391 if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002392 (I.getType())->getValueAPF()))
2393 return ReplaceInstUsesWith(I, LHS);
2394 }
2395
2396 if (isa<PHINode>(LHS))
2397 if (Instruction *NV = FoldOpIntoPhi(I))
2398 return NV;
2399 }
2400
2401 // -A + B --> B - A
2402 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002403 if (Value *LHSV = dyn_castFNegVal(LHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002404 return BinaryOperator::CreateFSub(RHS, LHSV);
2405
2406 // A + -B --> A - B
2407 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002408 if (Value *V = dyn_castFNegVal(RHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002409 return BinaryOperator::CreateFSub(LHS, V);
2410
2411 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2412 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2413 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2414 return ReplaceInstUsesWith(I, LHS);
2415
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002416 // Check for (add double (sitofp x), y), see if we can merge this into an
2417 // integer add followed by a promotion.
2418 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2419 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2420 // ... if the constant fits in the integer value. This is useful for things
2421 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2422 // requires a constant pool load, and generally allows the add to be better
2423 // instcombined.
2424 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2425 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002426 Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002427 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002428 Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002429 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2430 // Insert the new integer add.
2431 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2432 CI, "addconv");
2433 InsertNewInstBefore(NewAdd, I);
2434 return new SIToFPInst(NewAdd, I.getType());
2435 }
2436 }
2437
2438 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2439 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2440 // Only do this if x/y have the same type, if at last one of them has a
2441 // single use (so we don't increase the number of int->fp conversions),
2442 // and if the integer add will not overflow.
2443 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2444 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2445 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2446 RHSConv->getOperand(0))) {
2447 // Insert the new integer add.
2448 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2449 RHSConv->getOperand(0),
2450 "addconv");
2451 InsertNewInstBefore(NewAdd, I);
2452 return new SIToFPInst(NewAdd, I.getType());
2453 }
2454 }
2455 }
2456
Chris Lattner7e708292002-06-25 16:13:24 +00002457 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002458}
2459
Chris Lattner7e708292002-06-25 16:13:24 +00002460Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002461 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002462
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002463 if (Op0 == Op1) // sub X, X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002464 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002465
Chris Lattner233f7dc2002-08-12 21:17:25 +00002466 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002467 if (Value *V = dyn_castNegVal(Op1, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002468 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002469
Chris Lattnere87597f2004-10-16 18:11:37 +00002470 if (isa<UndefValue>(Op0))
2471 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2472 if (isa<UndefValue>(Op1))
2473 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2474
Chris Lattnerd65460f2003-11-05 01:06:05 +00002475 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2476 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002477 if (C->isAllOnesValue())
Owen Anderson73c6b712009-07-13 20:58:05 +00002478 return BinaryOperator::CreateNot(*Context, Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002479
Chris Lattnerd65460f2003-11-05 01:06:05 +00002480 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002481 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002482 if (match(Op1, m_Not(m_Value(X)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002483 return BinaryOperator::CreateAdd(X, AddOne(C, Context));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002484
Chris Lattner76b7a062007-01-15 07:02:54 +00002485 // -(X >>u 31) -> (X >>s 31)
2486 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002487 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002488 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002489 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002490 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002491 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002492 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002493 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002494 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002495 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002496 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002497 }
2498 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002499 }
2500 else if (SI->getOpcode() == Instruction::AShr) {
2501 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2502 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002503 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002504 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002505 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002506 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002507 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002508 }
2509 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002510 }
2511 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002512 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002513
2514 // Try to fold constant sub into select arguments.
2515 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002516 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002517 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002518
2519 // C - zext(bool) -> bool ? C - 1 : C
2520 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2521 if (ZI->getSrcTy() == Type::Int1Ty)
2522 return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002523 }
2524
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002525 if (I.getType() == Type::Int1Ty)
2526 return BinaryOperator::CreateXor(Op0, Op1);
2527
Chris Lattner43d84d62005-04-07 16:15:25 +00002528 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002529 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002530 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002531 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2532 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002533 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002534 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0),
2535 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002536 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2537 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2538 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002539 return BinaryOperator::CreateSub(
2540 Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002541 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002542 }
2543
Chris Lattnerfd059242003-10-15 16:48:29 +00002544 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002545 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2546 // is not used by anyone else...
2547 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002548 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002549 // Swap the two operands of the subexpr...
2550 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2551 Op1I->setOperand(0, IIOp1);
2552 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002553
Chris Lattnera2881962003-02-18 19:28:33 +00002554 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002555 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002556 }
2557
2558 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2559 //
2560 if (Op1I->getOpcode() == Instruction::And &&
2561 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2562 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2563
Chris Lattnerf523d062004-06-09 05:08:07 +00002564 Value *NewNot =
Owen Anderson73c6b712009-07-13 20:58:05 +00002565 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
2566 OtherOp, "B.not"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002567 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002568 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002569
Reid Spencerac5209e2006-10-16 23:08:08 +00002570 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002571 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002572 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002573 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002574 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002575 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002576 Context->getConstantExprNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002577
Chris Lattnerad3448c2003-02-18 19:57:07 +00002578 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002579 ConstantInt *C2 = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00002580 if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2581 Constant *CP1 =
2582 Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002583 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002584 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002585 }
Chris Lattner40371712002-05-09 01:29:19 +00002586 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002587 }
Chris Lattnera2881962003-02-18 19:28:33 +00002588
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002589 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2590 if (Op0I->getOpcode() == Instruction::Add) {
2591 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2592 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2593 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2594 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2595 } else if (Op0I->getOpcode() == Instruction::Sub) {
2596 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002597 return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2598 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002599 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002600 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002601
Chris Lattner50af16a2004-11-13 19:50:12 +00002602 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002603 if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002604 if (X == Op1) // X*C - X --> X * (C-1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002605 return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002606
Chris Lattner50af16a2004-11-13 19:50:12 +00002607 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Owen Andersond672ecb2009-07-03 00:17:18 +00002608 if (X == dyn_castFoldableMul(Op1, C2, Context))
2609 return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002610 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002611 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002612}
2613
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002614Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2615 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2616
2617 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002618 if (Value *V = dyn_castFNegVal(Op1, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002619 return BinaryOperator::CreateFAdd(Op0, V);
2620
2621 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2622 if (Op1I->getOpcode() == Instruction::FAdd) {
2623 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002624 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2625 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002626 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002627 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2628 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002629 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002630 }
2631
2632 return 0;
2633}
2634
Chris Lattnera0141b92007-07-15 20:42:37 +00002635/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2636/// comparison only checks the sign bit. If it only checks the sign bit, set
2637/// TrueIfSigned if the result of the comparison is true when the input value is
2638/// signed.
2639static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2640 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002641 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002642 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2643 TrueIfSigned = true;
2644 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002645 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2646 TrueIfSigned = true;
2647 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002648 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2649 TrueIfSigned = false;
2650 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002651 case ICmpInst::ICMP_UGT:
2652 // True if LHS u> RHS and RHS == high-bit-mask - 1
2653 TrueIfSigned = true;
2654 return RHS->getValue() ==
2655 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2656 case ICmpInst::ICMP_UGE:
2657 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2658 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002659 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002660 default:
2661 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002662 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002663}
2664
Chris Lattner7e708292002-06-25 16:13:24 +00002665Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002666 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002667 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002668
Dan Gohman77b81fe2009-06-04 17:12:12 +00002669 // TODO: If Op1 is undef and Op0 is finite, return zero.
2670 if (!I.getType()->isFPOrFPVector() &&
2671 isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002672 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002673
Chris Lattner233f7dc2002-08-12 21:17:25 +00002674 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002675 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2676 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002677
2678 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002679 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002680 if (SI->getOpcode() == Instruction::Shl)
2681 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002682 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002683 Context->getConstantExprShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002684
Zhou Sheng843f07672007-04-19 05:39:12 +00002685 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002686 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2687 if (CI->equalsInt(1)) // X * 1 == X
2688 return ReplaceInstUsesWith(I, Op0);
2689 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002690 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002691
Zhou Sheng97b52c22007-03-29 01:57:21 +00002692 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002693 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002694 return BinaryOperator::CreateShl(Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00002695 Context->getConstantInt(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002696 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002697 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002698 if (Op1->isNullValue())
2699 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002700
2701 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2702 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002703 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002704
2705 // As above, vector X*splat(1.0) -> X in all defined cases.
2706 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002707 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2708 if (CI->equalsInt(1))
2709 return ReplaceInstUsesWith(I, Op0);
2710 }
2711 }
Chris Lattnera2881962003-02-18 19:28:33 +00002712 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002713
2714 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2715 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002716 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002717 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002718 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002719 Op1, "tmp");
2720 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00002721 Value *C1C2 = Context->getConstantExprMul(Op1,
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002722 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002723 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002724
2725 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002726
2727 // Try to fold constant mul into select arguments.
2728 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002729 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002730 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002731
2732 if (isa<PHINode>(Op0))
2733 if (Instruction *NV = FoldOpIntoPhi(I))
2734 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002735 }
2736
Owen Andersond672ecb2009-07-03 00:17:18 +00002737 if (Value *Op0v = dyn_castNegVal(Op0, Context)) // -X * -Y = X*Y
2738 if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002739 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002740
Nick Lewycky0c730792008-11-21 07:33:58 +00002741 // (X / Y) * Y = X - (X % Y)
2742 // (X / Y) * -Y = (X % Y) - X
2743 {
2744 Value *Op1 = I.getOperand(1);
2745 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2746 if (!BO ||
2747 (BO->getOpcode() != Instruction::UDiv &&
2748 BO->getOpcode() != Instruction::SDiv)) {
2749 Op1 = Op0;
2750 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2751 }
Owen Andersond672ecb2009-07-03 00:17:18 +00002752 Value *Neg = dyn_castNegVal(Op1, Context);
Nick Lewycky0c730792008-11-21 07:33:58 +00002753 if (BO && BO->hasOneUse() &&
2754 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2755 (BO->getOpcode() == Instruction::UDiv ||
2756 BO->getOpcode() == Instruction::SDiv)) {
2757 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2758
2759 Instruction *Rem;
2760 if (BO->getOpcode() == Instruction::UDiv)
2761 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2762 else
2763 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2764
2765 InsertNewInstBefore(Rem, I);
2766 Rem->takeName(BO);
2767
2768 if (Op1BO == Op1)
2769 return BinaryOperator::CreateSub(Op0BO, Rem);
2770 else
2771 return BinaryOperator::CreateSub(Rem, Op0BO);
2772 }
2773 }
2774
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002775 if (I.getType() == Type::Int1Ty)
2776 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2777
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002778 // If one of the operands of the multiply is a cast from a boolean value, then
2779 // we know the bool is either zero or one, so this is a 'masking' multiply.
2780 // See if we can simplify things based on how the boolean was originally
2781 // formed.
2782 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002783 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002784 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002785 BoolCast = CI;
2786 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002787 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
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 Spencere4d87aa2006-12-23 06:05:41 +00002791 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002792 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2793 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002794 bool TIS = false;
2795
Reid Spencere4d87aa2006-12-23 06:05:41 +00002796 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002797 // multiply into a shift/and combination.
2798 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002799 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2800 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002801 // Shift the X value right to turn it into "all signbits".
Owen Andersond672ecb2009-07-03 00:17:18 +00002802 Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002803 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002804 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002805 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002806 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002807 BoolCast->getOperand(0)->getName()+
2808 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002809
2810 // If the multiply type is not the same as the source type, sign extend
2811 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002812 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002813 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2814 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002815 Instruction::CastOps opcode =
2816 (SrcBits == DstBits ? Instruction::BitCast :
2817 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2818 V = InsertCastBefore(opcode, V, I.getType(), I);
2819 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002820
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002821 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002822 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002823 }
2824 }
2825 }
2826
Chris Lattner7e708292002-06-25 16:13:24 +00002827 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002828}
2829
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002830Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2831 bool Changed = SimplifyCommutative(I);
2832 Value *Op0 = I.getOperand(0);
2833
2834 // Simplify mul instructions with a constant RHS...
2835 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2836 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2837 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2838 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2839 if (Op1F->isExactlyValue(1.0))
2840 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2841 } else if (isa<VectorType>(Op1->getType())) {
2842 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2843 // As above, vector X*splat(1.0) -> X in all defined cases.
2844 if (Constant *Splat = Op1V->getSplatValue()) {
2845 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2846 if (F->isExactlyValue(1.0))
2847 return ReplaceInstUsesWith(I, Op0);
2848 }
2849 }
2850 }
2851
2852 // Try to fold constant mul into select arguments.
2853 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2854 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2855 return R;
2856
2857 if (isa<PHINode>(Op0))
2858 if (Instruction *NV = FoldOpIntoPhi(I))
2859 return NV;
2860 }
2861
Owen Andersond672ecb2009-07-03 00:17:18 +00002862 if (Value *Op0v = dyn_castFNegVal(Op0, Context)) // -X * -Y = X*Y
2863 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002864 return BinaryOperator::CreateFMul(Op0v, Op1v);
2865
2866 return Changed ? &I : 0;
2867}
2868
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002869/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2870/// instruction.
2871bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2872 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2873
2874 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2875 int NonNullOperand = -1;
2876 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2877 if (ST->isNullValue())
2878 NonNullOperand = 2;
2879 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2880 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2881 if (ST->isNullValue())
2882 NonNullOperand = 1;
2883
2884 if (NonNullOperand == -1)
2885 return false;
2886
2887 Value *SelectCond = SI->getOperand(0);
2888
2889 // Change the div/rem to use 'Y' instead of the select.
2890 I.setOperand(1, SI->getOperand(NonNullOperand));
2891
2892 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2893 // problem. However, the select, or the condition of the select may have
2894 // multiple uses. Based on our knowledge that the operand must be non-zero,
2895 // propagate the known value for the select into other uses of it, and
2896 // propagate a known value of the condition into its other users.
2897
2898 // If the select and condition only have a single use, don't bother with this,
2899 // early exit.
2900 if (SI->use_empty() && SelectCond->hasOneUse())
2901 return true;
2902
2903 // Scan the current block backward, looking for other uses of SI.
2904 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2905
2906 while (BBI != BBFront) {
2907 --BBI;
2908 // If we found a call to a function, we can't assume it will return, so
2909 // information from below it cannot be propagated above it.
2910 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2911 break;
2912
2913 // Replace uses of the select or its condition with the known values.
2914 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2915 I != E; ++I) {
2916 if (*I == SI) {
2917 *I = SI->getOperand(NonNullOperand);
2918 AddToWorkList(BBI);
2919 } else if (*I == SelectCond) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002920 *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2921 Context->getConstantIntFalse();
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002922 AddToWorkList(BBI);
2923 }
2924 }
2925
2926 // If we past the instruction, quit looking for it.
2927 if (&*BBI == SI)
2928 SI = 0;
2929 if (&*BBI == SelectCond)
2930 SelectCond = 0;
2931
2932 // If we ran out of things to eliminate, break out of the loop.
2933 if (SelectCond == 0 && SI == 0)
2934 break;
2935
2936 }
2937 return true;
2938}
2939
2940
Reid Spencer1628cec2006-10-26 06:15:43 +00002941/// This function implements the transforms on div instructions that work
2942/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2943/// used by the visitors to those instructions.
2944/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002945Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002946 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002947
Chris Lattner50b2ca42008-02-19 06:12:18 +00002948 // undef / X -> 0 for integer.
2949 // undef / X -> undef for FP (the undef could be a snan).
2950 if (isa<UndefValue>(Op0)) {
2951 if (Op0->getType()->isFPOrFPVector())
2952 return ReplaceInstUsesWith(I, Op0);
Owen Andersond672ecb2009-07-03 00:17:18 +00002953 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002954 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002955
2956 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002957 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002958 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002959
Reid Spencer1628cec2006-10-26 06:15:43 +00002960 return 0;
2961}
Misha Brukmanfd939082005-04-21 23:48:37 +00002962
Reid Spencer1628cec2006-10-26 06:15:43 +00002963/// This function implements the transforms common to both integer division
2964/// instructions (udiv and sdiv). It is called by the visitors to those integer
2965/// division instructions.
2966/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002967Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002968 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2969
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002970 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002971 if (Op0 == Op1) {
2972 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002973 Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002974 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00002975 return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002976 }
2977
Owen Andersond672ecb2009-07-03 00:17:18 +00002978 Constant *CI = Context->getConstantInt(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002979 return ReplaceInstUsesWith(I, CI);
2980 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002981
Reid Spencer1628cec2006-10-26 06:15:43 +00002982 if (Instruction *Common = commonDivTransforms(I))
2983 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002984
2985 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2986 // This does not apply for fdiv.
2987 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2988 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002989
2990 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2991 // div X, 1 == X
2992 if (RHS->equalsInt(1))
2993 return ReplaceInstUsesWith(I, Op0);
2994
2995 // (X / C1) / C2 -> X / (C1*C2)
2996 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2997 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2998 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002999 if (MultiplyOverflows(RHS, LHSRHS,
3000 I.getOpcode()==Instruction::SDiv, Context))
3001 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003002 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003003 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00003004 Context->getConstantExprMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003005 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003006
Reid Spencerbca0e382007-03-23 20:05:17 +00003007 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003008 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3009 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3010 return R;
3011 if (isa<PHINode>(Op0))
3012 if (Instruction *NV = FoldOpIntoPhi(I))
3013 return NV;
3014 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003015 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003016
Chris Lattnera2881962003-02-18 19:28:33 +00003017 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003018 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003019 if (LHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00003020 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003021
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003022 // It can't be division by zero, hence it must be division by one.
3023 if (I.getType() == Type::Int1Ty)
3024 return ReplaceInstUsesWith(I, Op0);
3025
Nick Lewycky895f0852008-11-27 20:21:08 +00003026 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3027 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3028 // div X, 1 == X
3029 if (X->isOne())
3030 return ReplaceInstUsesWith(I, Op0);
3031 }
3032
Reid Spencer1628cec2006-10-26 06:15:43 +00003033 return 0;
3034}
3035
3036Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3037 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3038
3039 // Handle the integer div common cases
3040 if (Instruction *Common = commonIDivTransforms(I))
3041 return Common;
3042
Reid Spencer1628cec2006-10-26 06:15:43 +00003043 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003044 // X udiv C^2 -> X >> C
3045 // Check to see if this is an unsigned division with an exact power of 2,
3046 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003047 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003048 return BinaryOperator::CreateLShr(Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00003049 Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003050
3051 // X udiv C, where C >= signbit
3052 if (C->getValue().isNegative()) {
Owen Anderson333c4002009-07-09 23:48:35 +00003053 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3054 ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky8ca52482008-11-27 22:41:10 +00003055 I);
Owen Andersond672ecb2009-07-03 00:17:18 +00003056 return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3057 Context->getConstantInt(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003058 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003059 }
3060
3061 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003062 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003063 if (RHSI->getOpcode() == Instruction::Shl &&
3064 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003065 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003066 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003067 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003068 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003069 if (uint32_t C2 = C1.logBase2()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003070 Constant *C2V = Context->getConstantInt(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003071 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003072 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003073 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003074 }
3075 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003076 }
3077
Reid Spencer1628cec2006-10-26 06:15:43 +00003078 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3079 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003080 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003081 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003082 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003083 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003084 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003085 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003086 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003087 // Construct the "on true" case of the select
Owen Andersond672ecb2009-07-03 00:17:18 +00003088 Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003089 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003090 Op0, TC, SI->getName()+".t");
3091 TSI = InsertNewInstBefore(TSI, I);
3092
3093 // Construct the "on false" case of the select
Owen Andersond672ecb2009-07-03 00:17:18 +00003094 Constant *FC = Context->getConstantInt(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003095 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003096 Op0, FC, SI->getName()+".f");
3097 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003098
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003099 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003100 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003101 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003102 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003103 return 0;
3104}
3105
Reid Spencer1628cec2006-10-26 06:15:43 +00003106Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3107 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3108
3109 // Handle the integer div common cases
3110 if (Instruction *Common = commonIDivTransforms(I))
3111 return Common;
3112
3113 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3114 // sdiv X, -1 == -X
3115 if (RHS->isAllOnesValue())
Owen Anderson0a5372e2009-07-13 04:09:18 +00003116 return BinaryOperator::CreateNeg(*Context, Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003117 }
3118
3119 // If the sign bits of both operands are zero (i.e. we can prove they are
3120 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003121 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003122 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003123 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003124 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003125 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003126 }
3127 }
3128
3129 return 0;
3130}
3131
3132Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3133 return commonDivTransforms(I);
3134}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003135
Reid Spencer0a783f72006-11-02 01:53:59 +00003136/// This function implements the transforms on rem instructions that work
3137/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3138/// is used by the visitors to those instructions.
3139/// @brief Transforms common to all three rem instructions
3140Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003141 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003142
Chris Lattner50b2ca42008-02-19 06:12:18 +00003143 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3144 if (I.getType()->isFPOrFPVector())
3145 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersond672ecb2009-07-03 00:17:18 +00003146 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003147 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003148 if (isa<UndefValue>(Op1))
3149 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003150
3151 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003152 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3153 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003154
Reid Spencer0a783f72006-11-02 01:53:59 +00003155 return 0;
3156}
3157
3158/// This function implements the transforms common to both integer remainder
3159/// instructions (urem and srem). It is called by the visitors to those integer
3160/// remainder instructions.
3161/// @brief Common integer remainder transforms
3162Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3163 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3164
3165 if (Instruction *common = commonRemTransforms(I))
3166 return common;
3167
Dale Johannesened6af242009-01-21 00:35:19 +00003168 // 0 % X == 0 for integer, we don't need to preserve faults!
3169 if (Constant *LHS = dyn_cast<Constant>(Op0))
3170 if (LHS->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00003171 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003172
Chris Lattner857e8cd2004-12-12 21:48:58 +00003173 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003174 // X % 0 == undef, we don't need to preserve faults!
3175 if (RHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00003176 return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003177
Chris Lattnera2881962003-02-18 19:28:33 +00003178 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003179 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003180
Chris Lattner97943922006-02-28 05:49:21 +00003181 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3182 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3183 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3184 return R;
3185 } else if (isa<PHINode>(Op0I)) {
3186 if (Instruction *NV = FoldOpIntoPhi(I))
3187 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003188 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003189
3190 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003191 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003192 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003193 }
Chris Lattnera2881962003-02-18 19:28:33 +00003194 }
3195
Reid Spencer0a783f72006-11-02 01:53:59 +00003196 return 0;
3197}
3198
3199Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3200 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3201
3202 if (Instruction *common = commonIRemTransforms(I))
3203 return common;
3204
3205 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3206 // X urem C^2 -> X and C
3207 // Check to see if this is an unsigned remainder with an exact power of 2,
3208 // if so, convert to a bitwise and.
3209 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003210 if (C->getValue().isPowerOf2())
Owen Andersond672ecb2009-07-03 00:17:18 +00003211 return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
Reid Spencer0a783f72006-11-02 01:53:59 +00003212 }
3213
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003214 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003215 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3216 if (RHSI->getOpcode() == Instruction::Shl &&
3217 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003218 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Anderson73c6b712009-07-13 20:58:05 +00003219 Constant *N1 = Context->getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003220 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003221 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003222 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003223 }
3224 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003225 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003226
Reid Spencer0a783f72006-11-02 01:53:59 +00003227 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3228 // where C1&C2 are powers of two.
3229 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3230 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3231 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3232 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003233 if ((STO->getValue().isPowerOf2()) &&
3234 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003235 Value *TrueAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003236 BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3237 SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003238 Value *FalseAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003239 BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3240 SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003241 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003242 }
3243 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003244 }
3245
Chris Lattner3f5b8772002-05-06 16:14:14 +00003246 return 0;
3247}
3248
Reid Spencer0a783f72006-11-02 01:53:59 +00003249Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3250 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3251
Dan Gohmancff55092007-11-05 23:16:33 +00003252 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003253 if (Instruction *common = commonIRemTransforms(I))
3254 return common;
3255
Owen Andersond672ecb2009-07-03 00:17:18 +00003256 if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
Nick Lewycky23c04302008-09-03 06:24:21 +00003257 if (!isa<Constant>(RHSNeg) ||
3258 (isa<ConstantInt>(RHSNeg) &&
3259 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003260 // X % -Y -> X % Y
3261 AddUsesToWorkList(I);
3262 I.setOperand(1, RHSNeg);
3263 return &I;
3264 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003265
Dan Gohmancff55092007-11-05 23:16:33 +00003266 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003267 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003268 if (I.getType()->isInteger()) {
3269 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3270 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3271 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003272 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003273 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003274 }
3275
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003276 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003277 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3278 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003279
Nick Lewycky9dce8732008-12-20 16:48:00 +00003280 bool hasNegative = false;
3281 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3282 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3283 if (RHS->getValue().isNegative())
3284 hasNegative = true;
3285
3286 if (hasNegative) {
3287 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003288 for (unsigned i = 0; i != VWidth; ++i) {
3289 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3290 if (RHS->getValue().isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00003291 Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003292 else
3293 Elts[i] = RHS;
3294 }
3295 }
3296
Owen Andersond672ecb2009-07-03 00:17:18 +00003297 Constant *NewRHSV = Context->getConstantVector(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003298 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003299 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003300 I.setOperand(1, NewRHSV);
3301 return &I;
3302 }
3303 }
3304 }
3305
Reid Spencer0a783f72006-11-02 01:53:59 +00003306 return 0;
3307}
3308
3309Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003310 return commonRemTransforms(I);
3311}
3312
Chris Lattner457dd822004-06-09 07:59:58 +00003313// isOneBitSet - Return true if there is exactly one bit set in the specified
3314// constant.
3315static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003316 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003317}
3318
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003319// isHighOnes - Return true if the constant is of the form 1+0+.
3320// This is the same as lowones(~X).
3321static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003322 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003323}
3324
Reid Spencere4d87aa2006-12-23 06:05:41 +00003325/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003326/// are carefully arranged to allow folding of expressions such as:
3327///
3328/// (A < B) | (A > B) --> (A != B)
3329///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003330/// Note that this is only valid if the first and second predicates have the
3331/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003332///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003333/// Three bits are used to represent the condition, as follows:
3334/// 0 A > B
3335/// 1 A == B
3336/// 2 A < B
3337///
3338/// <=> Value Definition
3339/// 000 0 Always false
3340/// 001 1 A > B
3341/// 010 2 A == B
3342/// 011 3 A >= B
3343/// 100 4 A < B
3344/// 101 5 A != B
3345/// 110 6 A <= B
3346/// 111 7 Always true
3347///
3348static unsigned getICmpCode(const ICmpInst *ICI) {
3349 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003350 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003351 case ICmpInst::ICMP_UGT: return 1; // 001
3352 case ICmpInst::ICMP_SGT: return 1; // 001
3353 case ICmpInst::ICMP_EQ: return 2; // 010
3354 case ICmpInst::ICMP_UGE: return 3; // 011
3355 case ICmpInst::ICMP_SGE: return 3; // 011
3356 case ICmpInst::ICMP_ULT: return 4; // 100
3357 case ICmpInst::ICMP_SLT: return 4; // 100
3358 case ICmpInst::ICMP_NE: return 5; // 101
3359 case ICmpInst::ICMP_ULE: return 6; // 110
3360 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003361 // True -> 7
3362 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003363 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003364 return 0;
3365 }
3366}
3367
Evan Cheng8db90722008-10-14 17:15:11 +00003368/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3369/// predicate into a three bit mask. It also returns whether it is an ordered
3370/// predicate by reference.
3371static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3372 isOrdered = false;
3373 switch (CC) {
3374 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3375 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003376 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3377 case FCmpInst::FCMP_UGT: return 1; // 001
3378 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3379 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003380 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3381 case FCmpInst::FCMP_UGE: return 3; // 011
3382 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3383 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003384 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3385 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003386 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3387 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003388 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003389 default:
3390 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003391 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003392 return 0;
3393 }
3394}
3395
Reid Spencere4d87aa2006-12-23 06:05:41 +00003396/// getICmpValue - This is the complement of getICmpCode, which turns an
3397/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003398/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003399/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003400static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003401 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003402 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003403 default: llvm_unreachable("Illegal ICmp code!");
Owen Andersond672ecb2009-07-03 00:17:18 +00003404 case 0: return Context->getConstantIntFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003405 case 1:
3406 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003407 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003408 else
Owen Anderson333c4002009-07-09 23:48:35 +00003409 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3410 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003411 case 3:
3412 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003413 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003414 else
Owen Anderson333c4002009-07-09 23:48:35 +00003415 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003416 case 4:
3417 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003418 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003419 else
Owen Anderson333c4002009-07-09 23:48:35 +00003420 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3421 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003422 case 6:
3423 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003424 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003425 else
Owen Anderson333c4002009-07-09 23:48:35 +00003426 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00003427 case 7: return Context->getConstantIntTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003428 }
3429}
3430
Evan Cheng8db90722008-10-14 17:15:11 +00003431/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3432/// opcode and two operands into either a FCmp instruction. isordered is passed
3433/// in to determine which kind of predicate to use in the new fcmp instruction.
3434static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003435 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003436 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003437 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003438 case 0:
3439 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003440 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003441 else
Owen Anderson333c4002009-07-09 23:48:35 +00003442 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003443 case 1:
3444 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003445 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003446 else
Owen Anderson333c4002009-07-09 23:48:35 +00003447 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003448 case 2:
3449 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003450 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003451 else
Owen Anderson333c4002009-07-09 23:48:35 +00003452 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003453 case 3:
3454 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003455 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003456 else
Owen Anderson333c4002009-07-09 23:48:35 +00003457 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003458 case 4:
3459 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003460 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003461 else
Owen Anderson333c4002009-07-09 23:48:35 +00003462 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003463 case 5:
3464 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003465 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003466 else
Owen Anderson333c4002009-07-09 23:48:35 +00003467 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003468 case 6:
3469 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003470 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003471 else
Owen Anderson333c4002009-07-09 23:48:35 +00003472 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00003473 case 7: return Context->getConstantIntTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003474 }
3475}
3476
Chris Lattnerb9553d62008-11-16 04:55:20 +00003477/// PredicatesFoldable - Return true if both predicates match sign or if at
3478/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003479static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3480 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003481 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3482 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003483}
3484
3485namespace {
3486// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3487struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003488 InstCombiner &IC;
3489 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003490 ICmpInst::Predicate pred;
3491 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3492 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3493 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003494 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003495 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3496 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003497 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3498 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003499 return false;
3500 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003501 Instruction *apply(Instruction &Log) const {
3502 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3503 if (ICI->getOperand(0) != LHS) {
3504 assert(ICI->getOperand(1) == LHS);
3505 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003506 }
3507
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003508 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003509 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003510 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003511 unsigned Code;
3512 switch (Log.getOpcode()) {
3513 case Instruction::And: Code = LHSCode & RHSCode; break;
3514 case Instruction::Or: Code = LHSCode | RHSCode; break;
3515 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003516 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003517 }
3518
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003519 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3520 ICmpInst::isSignedPredicate(ICI->getPredicate());
3521
Owen Andersond672ecb2009-07-03 00:17:18 +00003522 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003523 if (Instruction *I = dyn_cast<Instruction>(RV))
3524 return I;
3525 // Otherwise, it's a constant boolean value...
3526 return IC.ReplaceInstUsesWith(Log, RV);
3527 }
3528};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003529} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003530
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003531// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3532// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003533// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003534Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003535 ConstantInt *OpRHS,
3536 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003537 BinaryOperator &TheAnd) {
3538 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003539 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003540 if (!Op->isShift())
Owen Andersond672ecb2009-07-03 00:17:18 +00003541 Together = Context->getConstantExprAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003542
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003543 switch (Op->getOpcode()) {
3544 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003545 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003546 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003547 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003548 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003549 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003550 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003551 }
3552 break;
3553 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003554 if (Together == AndRHS) // (X | C) & C --> C
3555 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003556
Chris Lattner6e7ba452005-01-01 16:22:27 +00003557 if (Op->hasOneUse() && Together != OpRHS) {
3558 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003559 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003560 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003561 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003562 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003563 }
3564 break;
3565 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003566 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003567 // Adding a one to a single bit bit-field should be turned into an XOR
3568 // of the bit. First thing to check is to see if this AND is with a
3569 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003570 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003571
3572 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003573 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003574 // Ok, at this point, we know that we are masking the result of the
3575 // ADD down to exactly one bit. If the constant we are adding has
3576 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003577 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003578
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003579 // Check to see if any bits below the one bit set in AndRHSV are set.
3580 if ((AddRHS & (AndRHSV-1)) == 0) {
3581 // If not, the only thing that can effect the output of the AND is
3582 // the bit specified by AndRHSV. If that bit is set, the effect of
3583 // the XOR is to toggle the bit. If it is clear, then the ADD has
3584 // no effect.
3585 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3586 TheAnd.setOperand(0, X);
3587 return &TheAnd;
3588 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003589 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003590 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003591 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003592 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003593 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003594 }
3595 }
3596 }
3597 }
3598 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003599
3600 case Instruction::Shl: {
3601 // We know that the AND will not produce any of the bits shifted in, so if
3602 // the anded constant includes them, clear them now!
3603 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003604 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003605 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003606 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003607 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003608
Zhou Sheng290bec52007-03-29 08:15:12 +00003609 if (CI->getValue() == ShlMask) {
3610 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003611 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3612 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003613 TheAnd.setOperand(1, CI);
3614 return &TheAnd;
3615 }
3616 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003617 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003618 case Instruction::LShr:
3619 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003620 // We know that the AND will not produce any of the bits shifted in, so if
3621 // the anded constant includes them, clear them now! This only applies to
3622 // unsigned shifts, because a signed shr may bring in set bits!
3623 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003624 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003625 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003626 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003627 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003628
Zhou Sheng290bec52007-03-29 08:15:12 +00003629 if (CI->getValue() == ShrMask) {
3630 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003631 return ReplaceInstUsesWith(TheAnd, Op);
3632 } else if (CI != AndRHS) {
3633 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3634 return &TheAnd;
3635 }
3636 break;
3637 }
3638 case Instruction::AShr:
3639 // Signed shr.
3640 // See if this is shifting in some sign extension, then masking it out
3641 // with an and.
3642 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003643 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003644 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003645 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003646 Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003647 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003648 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003649 // Make the argument unsigned.
3650 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003651 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003652 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003653 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003654 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003655 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003656 }
3657 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003658 }
3659 return 0;
3660}
3661
Chris Lattner8b170942002-08-09 23:47:40 +00003662
Chris Lattnera96879a2004-09-29 17:40:11 +00003663/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3664/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003665/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3666/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003667/// insert new instructions.
3668Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003669 bool isSigned, bool Inside,
3670 Instruction &IB) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003671 assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003672 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003673 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003674
Chris Lattnera96879a2004-09-29 17:40:11 +00003675 if (Inside) {
3676 if (Lo == Hi) // Trivially false.
Owen Anderson333c4002009-07-09 23:48:35 +00003677 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003678
Reid Spencere4d87aa2006-12-23 06:05:41 +00003679 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003680 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003681 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003682 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Owen Anderson333c4002009-07-09 23:48:35 +00003683 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003684 }
3685
3686 // Emit V-Lo <u Hi-Lo
Owen Andersond672ecb2009-07-03 00:17:18 +00003687 Constant *NegLo = Context->getConstantExprNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003688 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003689 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003690 Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003691 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003692 }
3693
3694 if (Lo == Hi) // Trivially true.
Owen Anderson333c4002009-07-09 23:48:35 +00003695 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003696
Reid Spencere4e40032007-03-21 23:19:50 +00003697 // V < Min || V >= Hi -> V > Hi-1
Owen Andersond672ecb2009-07-03 00:17:18 +00003698 Hi = SubOne(cast<ConstantInt>(Hi), Context);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003699 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003700 ICmpInst::Predicate pred = (isSigned ?
3701 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Owen Anderson333c4002009-07-09 23:48:35 +00003702 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003703 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003704
Reid Spencere4e40032007-03-21 23:19:50 +00003705 // Emit V-Lo >u Hi-1-Lo
3706 // Note that Hi has already had one subtracted from it, above.
Owen Andersond672ecb2009-07-03 00:17:18 +00003707 ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003708 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003709 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003710 Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003711 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003712}
3713
Chris Lattner7203e152005-09-18 07:22:02 +00003714// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3715// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3716// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3717// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003718static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003719 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003720 uint32_t BitWidth = Val->getType()->getBitWidth();
3721 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003722
3723 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003724 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003725 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003726 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003727 return true;
3728}
3729
Chris Lattner7203e152005-09-18 07:22:02 +00003730/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3731/// where isSub determines whether the operator is a sub. If we can fold one of
3732/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003733///
3734/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3735/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3736/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3737///
3738/// return (A +/- B).
3739///
3740Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003741 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003742 Instruction &I) {
3743 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3744 if (!LHSI || LHSI->getNumOperands() != 2 ||
3745 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3746
3747 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3748
3749 switch (LHSI->getOpcode()) {
3750 default: return 0;
3751 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00003752 if (Context->getConstantExprAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003753 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003754 if ((Mask->getValue().countLeadingZeros() +
3755 Mask->getValue().countPopulation()) ==
3756 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003757 break;
3758
3759 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3760 // part, we don't need any explicit masks to take them out of A. If that
3761 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003762 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003763 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003764 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003765 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003766 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003767 break;
3768 }
3769 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003770 return 0;
3771 case Instruction::Or:
3772 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003773 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003774 if ((Mask->getValue().countLeadingZeros() +
3775 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersond672ecb2009-07-03 00:17:18 +00003776 && Context->getConstantExprAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003777 break;
3778 return 0;
3779 }
3780
3781 Instruction *New;
3782 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003783 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003784 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003785 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003786 return InsertNewInstBefore(New, I);
3787}
3788
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003789/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3790Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3791 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003792 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003793 ConstantInt *LHSCst, *RHSCst;
3794 ICmpInst::Predicate LHSCC, RHSCC;
3795
Chris Lattnerea065fb2008-11-16 05:10:52 +00003796 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003797 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3798 m_ConstantInt(LHSCst)), *Context) ||
3799 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3800 m_ConstantInt(RHSCst)), *Context))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003801 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003802
3803 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3804 // where C is a power of 2
3805 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3806 LHSCst->getValue().isPowerOf2()) {
3807 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3808 InsertNewInstBefore(NewOr, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003809 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003810 }
3811
3812 // From here on, we only handle:
3813 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3814 if (Val != Val2) return 0;
3815
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003816 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3817 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3818 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3819 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3820 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3821 return 0;
3822
3823 // We can't fold (ugt x, C) & (sgt x, C2).
3824 if (!PredicatesFoldable(LHSCC, RHSCC))
3825 return 0;
3826
3827 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003828 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003829 if (ICmpInst::isSignedPredicate(LHSCC) ||
3830 (ICmpInst::isEquality(LHSCC) &&
3831 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003832 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003833 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003834 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3835
3836 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003837 std::swap(LHS, RHS);
3838 std::swap(LHSCst, RHSCst);
3839 std::swap(LHSCC, RHSCC);
3840 }
3841
3842 // At this point, we know we have have two icmp instructions
3843 // comparing a value against two constants and and'ing the result
3844 // together. Because of the above check, we know that we only have
3845 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3846 // (from the FoldICmpLogical check above), that the two constants
3847 // are not equal and that the larger constant is on the RHS
3848 assert(LHSCst != RHSCst && "Compares not folded above?");
3849
3850 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003851 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003852 case ICmpInst::ICMP_EQ:
3853 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003854 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003855 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3856 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3857 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Andersond672ecb2009-07-03 00:17:18 +00003858 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003859 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3860 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3861 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3862 return ReplaceInstUsesWith(I, LHS);
3863 }
3864 case ICmpInst::ICMP_NE:
3865 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003866 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003867 case ICmpInst::ICMP_ULT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003868 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003869 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003870 break; // (X != 13 & X u< 15) -> no change
3871 case ICmpInst::ICMP_SLT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003872 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003873 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003874 break; // (X != 13 & X s< 15) -> no change
3875 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3876 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3877 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3878 return ReplaceInstUsesWith(I, RHS);
3879 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003880 if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3881 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003882 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3883 Val->getName()+".off");
3884 InsertNewInstBefore(Add, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003885 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
Owen Andersond672ecb2009-07-03 00:17:18 +00003886 Context->getConstantInt(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003887 }
3888 break; // (X != 13 & X != 15) -> no change
3889 }
3890 break;
3891 case ICmpInst::ICMP_ULT:
3892 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003893 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003894 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3895 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Andersond672ecb2009-07-03 00:17:18 +00003896 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003897 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3898 break;
3899 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3900 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3901 return ReplaceInstUsesWith(I, LHS);
3902 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3903 break;
3904 }
3905 break;
3906 case ICmpInst::ICMP_SLT:
3907 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003908 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003909 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3910 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Andersond672ecb2009-07-03 00:17:18 +00003911 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003912 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3913 break;
3914 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3915 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3916 return ReplaceInstUsesWith(I, LHS);
3917 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3918 break;
3919 }
3920 break;
3921 case ICmpInst::ICMP_UGT:
3922 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003923 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003924 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3925 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3926 return ReplaceInstUsesWith(I, RHS);
3927 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3928 break;
3929 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003930 if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003931 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003932 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003933 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003934 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3935 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003936 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3937 break;
3938 }
3939 break;
3940 case ICmpInst::ICMP_SGT:
3941 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003942 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003943 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3944 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3945 return ReplaceInstUsesWith(I, RHS);
3946 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3947 break;
3948 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003949 if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003950 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003951 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003952 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003953 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3954 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003955 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3956 break;
3957 }
3958 break;
3959 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003960
3961 return 0;
3962}
3963
3964
Chris Lattner7e708292002-06-25 16:13:24 +00003965Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003966 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003967 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003968
Chris Lattnere87597f2004-10-16 18:11:37 +00003969 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003970 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003971
Chris Lattner6e7ba452005-01-01 16:22:27 +00003972 // and X, X = X
3973 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003974 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003975
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003976 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003977 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00003978 if (SimplifyDemandedInstructionBits(I))
3979 return &I;
3980 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003981 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003982 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003983 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003984 } else if (isa<ConstantAggregateZero>(Op1)) {
3985 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003986 }
3987 }
Dan Gohman6de29f82009-06-15 22:12:54 +00003988
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003989 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003990 const APInt& AndRHSMask = AndRHS->getValue();
3991 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003992
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003993 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003994 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003995 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003996 Value *Op0LHS = Op0I->getOperand(0);
3997 Value *Op0RHS = Op0I->getOperand(1);
3998 switch (Op0I->getOpcode()) {
3999 case Instruction::Xor:
4000 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004001 // If the mask is only needed on one incoming arm, push it up.
4002 if (Op0I->hasOneUse()) {
4003 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4004 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004005 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004006 Op0RHS->getName()+".masked");
4007 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004008 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004009 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004010 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004011 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004012 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4013 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004014 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004015 Op0LHS->getName()+".masked");
4016 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004017 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004018 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4019 }
4020 }
4021
Chris Lattner6e7ba452005-01-01 16:22:27 +00004022 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004023 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004024 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4025 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4026 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4027 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004028 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004029 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004030 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004031 break;
4032
4033 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004034 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4035 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4036 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4037 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004038 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004039
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004040 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4041 // has 1's for all bits that the subtraction with A might affect.
4042 if (Op0I->hasOneUse()) {
4043 uint32_t BitWidth = AndRHSMask.getBitWidth();
4044 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4045 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4046
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004047 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004048 if (!(A && A->isZero()) && // avoid infinite recursion.
4049 MaskedValueIsZero(Op0LHS, Mask)) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00004050 Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004051 InsertNewInstBefore(NewNeg, I);
4052 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4053 }
4054 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004055 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004056
4057 case Instruction::Shl:
4058 case Instruction::LShr:
4059 // (1 << x) & 1 --> zext(x == 0)
4060 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004061 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Owen Anderson333c4002009-07-09 23:48:35 +00004062 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4063 Op0RHS, Context->getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004064 InsertNewInstBefore(NewICmp, I);
4065 return new ZExtInst(NewICmp, I.getType());
4066 }
4067 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004068 }
4069
Chris Lattner58403262003-07-23 19:25:52 +00004070 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004071 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004072 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004073 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004074 // If this is an integer truncation or change from signed-to-unsigned, and
4075 // if the source is an and/or with immediate, transform it. This
4076 // frequently occurs for bitfield accesses.
4077 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004078 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004079 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004080 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004081 if (CastOp->getOpcode() == Instruction::And) {
4082 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004083 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4084 // This will fold the two constants together, which may allow
4085 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004086 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004087 CastOp->getOperand(0), I.getType(),
4088 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004089 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004090 // trunc_or_bitcast(C1)&C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004091 Constant *C3 =
4092 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4093 C3 = Context->getConstantExprAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004094 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004095 } else if (CastOp->getOpcode() == Instruction::Or) {
4096 // Change: and (cast (or X, C1) to T), C2
4097 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004098 Constant *C3 =
4099 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4100 if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4101 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004102 return ReplaceInstUsesWith(I, AndRHS);
4103 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004104 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004105 }
Chris Lattner06782f82003-07-23 19:36:21 +00004106 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004107
4108 // Try to fold constant and into select arguments.
4109 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004110 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004111 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004112 if (isa<PHINode>(Op0))
4113 if (Instruction *NV = FoldOpIntoPhi(I))
4114 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004115 }
4116
Owen Andersond672ecb2009-07-03 00:17:18 +00004117 Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4118 Value *Op1NotVal = dyn_castNotVal(Op1, Context);
Chris Lattnera2881962003-02-18 19:28:33 +00004119
Chris Lattner5b62aa72004-06-18 06:07:51 +00004120 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00004121 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004122
Misha Brukmancb6267b2004-07-30 12:50:08 +00004123 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004124 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004125 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004126 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004127 InsertNewInstBefore(Or, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004128 return BinaryOperator::CreateNot(*Context, Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004129 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004130
4131 {
Chris Lattner003b6202007-06-15 05:58:24 +00004132 Value *A = 0, *B = 0, *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004133 if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004134 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4135 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004136
4137 // (A|B) & ~(A&B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004138 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004139 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004140 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004141 }
4142 }
4143
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004144 if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004145 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4146 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004147
4148 // ~(A&B) & (A|B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004149 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004150 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004151 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004152 }
4153 }
Chris Lattner64daab52006-04-01 08:03:55 +00004154
4155 if (Op0->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004156 match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004157 if (A == Op1) { // (A^B)&A -> A&(A^B)
4158 I.swapOperands(); // Simplify below
4159 std::swap(Op0, Op1);
4160 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4161 cast<BinaryOperator>(Op0)->swapOperands();
4162 I.swapOperands(); // Simplify below
4163 std::swap(Op0, Op1);
4164 }
4165 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004166
Chris Lattner64daab52006-04-01 08:03:55 +00004167 if (Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004168 match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004169 if (B == Op0) { // B&(A^B) -> B&(B^A)
4170 cast<BinaryOperator>(Op1)->swapOperands();
4171 std::swap(A, B);
4172 }
4173 if (A == Op0) { // A&(A^B) -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00004174 Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004175 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004176 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004177 }
4178 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004179
4180 // (A&((~A)|B)) -> A&B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004181 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4182 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004183 return BinaryOperator::CreateAnd(A, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004184 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4185 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004186 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004187 }
4188
Reid Spencere4d87aa2006-12-23 06:05:41 +00004189 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4190 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004191 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004192 return R;
4193
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004194 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4195 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4196 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004197 }
4198
Chris Lattner6fc205f2006-05-05 06:39:07 +00004199 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004200 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4201 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4202 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4203 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004204 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004205 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004206 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4207 I.getType(), TD) &&
4208 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4209 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004210 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004211 Op1C->getOperand(0),
4212 I.getName());
4213 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004214 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004215 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004216 }
Chris Lattnere511b742006-11-14 07:46:50 +00004217
4218 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004219 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4220 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4221 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004222 SI0->getOperand(1) == SI1->getOperand(1) &&
4223 (SI0->hasOneUse() || SI1->hasOneUse())) {
4224 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004225 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004226 SI1->getOperand(0),
4227 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004228 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004229 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004230 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004231 }
4232
Evan Cheng8db90722008-10-14 17:15:11 +00004233 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004234 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4235 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4236 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng8db90722008-10-14 17:15:11 +00004237 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4238 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner99c65742007-10-24 05:38:08 +00004239 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4240 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4241 // If either of the constants are nans, then the whole thing returns
4242 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004243 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersond672ecb2009-07-03 00:17:18 +00004244 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00004245 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
4246 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner99c65742007-10-24 05:38:08 +00004247 }
Evan Cheng8db90722008-10-14 17:15:11 +00004248 } else {
4249 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4250 FCmpInst::Predicate Op0CC, Op1CC;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004251 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4252 m_Value(Op0RHS)), *Context) &&
4253 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4254 m_Value(Op1RHS)), *Context)) {
Evan Cheng4990b252008-10-14 18:13:38 +00004255 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4256 // Swap RHS operands to match LHS.
4257 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4258 std::swap(Op1LHS, Op1RHS);
4259 }
Evan Cheng8db90722008-10-14 17:15:11 +00004260 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4261 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4262 if (Op0CC == Op1CC)
Owen Anderson333c4002009-07-09 23:48:35 +00004263 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4264 Op0LHS, Op0RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00004265 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4266 Op1CC == FCmpInst::FCMP_FALSE)
Owen Andersond672ecb2009-07-03 00:17:18 +00004267 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng8db90722008-10-14 17:15:11 +00004268 else if (Op0CC == FCmpInst::FCMP_TRUE)
4269 return ReplaceInstUsesWith(I, Op1);
4270 else if (Op1CC == FCmpInst::FCMP_TRUE)
4271 return ReplaceInstUsesWith(I, Op0);
4272 bool Op0Ordered;
4273 bool Op1Ordered;
4274 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4275 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4276 if (Op1Pred == 0) {
4277 std::swap(Op0, Op1);
4278 std::swap(Op0Pred, Op1Pred);
4279 std::swap(Op0Ordered, Op1Ordered);
4280 }
4281 if (Op0Pred == 0) {
4282 // uno && ueq -> uno && (uno || eq) -> ueq
4283 // ord && olt -> ord && (ord && lt) -> olt
4284 if (Op0Ordered == Op1Ordered)
4285 return ReplaceInstUsesWith(I, Op1);
4286 // uno && oeq -> uno && (ord && eq) -> false
4287 // uno && ord -> false
4288 if (!Op0Ordered)
Owen Andersond672ecb2009-07-03 00:17:18 +00004289 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng8db90722008-10-14 17:15:11 +00004290 // ord && ueq -> ord && (uno || eq) -> oeq
4291 return cast<Instruction>(getFCmpValue(true, Op1Pred,
Owen Andersond672ecb2009-07-03 00:17:18 +00004292 Op0LHS, Op0RHS, Context));
Evan Cheng8db90722008-10-14 17:15:11 +00004293 }
4294 }
4295 }
4296 }
Chris Lattner99c65742007-10-24 05:38:08 +00004297 }
4298 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004299
Chris Lattner7e708292002-06-25 16:13:24 +00004300 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004301}
4302
Chris Lattner8c34cd22008-10-05 02:13:19 +00004303/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4304/// capable of providing pieces of a bswap. The subexpression provides pieces
4305/// of a bswap if it is proven that each of the non-zero bytes in the output of
4306/// the expression came from the corresponding "byte swapped" byte in some other
4307/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4308/// we know that the expression deposits the low byte of %X into the high byte
4309/// of the bswap result and that all other bytes are zero. This expression is
4310/// accepted, the high byte of ByteValues is set to X to indicate a correct
4311/// match.
4312///
4313/// This function returns true if the match was unsuccessful and false if so.
4314/// On entry to the function the "OverallLeftShift" is a signed integer value
4315/// indicating the number of bytes that the subexpression is later shifted. For
4316/// example, if the expression is later right shifted by 16 bits, the
4317/// OverallLeftShift value would be -2 on entry. This is used to specify which
4318/// byte of ByteValues is actually being set.
4319///
4320/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4321/// byte is masked to zero by a user. For example, in (X & 255), X will be
4322/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4323/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4324/// always in the local (OverallLeftShift) coordinate space.
4325///
4326static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4327 SmallVector<Value*, 8> &ByteValues) {
4328 if (Instruction *I = dyn_cast<Instruction>(V)) {
4329 // If this is an or instruction, it may be an inner node of the bswap.
4330 if (I->getOpcode() == Instruction::Or) {
4331 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4332 ByteValues) ||
4333 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4334 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004335 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004336
4337 // If this is a logical shift by a constant multiple of 8, recurse with
4338 // OverallLeftShift and ByteMask adjusted.
4339 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4340 unsigned ShAmt =
4341 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4342 // Ensure the shift amount is defined and of a byte value.
4343 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4344 return true;
4345
4346 unsigned ByteShift = ShAmt >> 3;
4347 if (I->getOpcode() == Instruction::Shl) {
4348 // X << 2 -> collect(X, +2)
4349 OverallLeftShift += ByteShift;
4350 ByteMask >>= ByteShift;
4351 } else {
4352 // X >>u 2 -> collect(X, -2)
4353 OverallLeftShift -= ByteShift;
4354 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004355 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004356 }
4357
4358 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4359 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4360
4361 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4362 ByteValues);
4363 }
4364
4365 // If this is a logical 'and' with a mask that clears bytes, clear the
4366 // corresponding bytes in ByteMask.
4367 if (I->getOpcode() == Instruction::And &&
4368 isa<ConstantInt>(I->getOperand(1))) {
4369 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4370 unsigned NumBytes = ByteValues.size();
4371 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4372 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4373
4374 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4375 // If this byte is masked out by a later operation, we don't care what
4376 // the and mask is.
4377 if ((ByteMask & (1 << i)) == 0)
4378 continue;
4379
4380 // If the AndMask is all zeros for this byte, clear the bit.
4381 APInt MaskB = AndMask & Byte;
4382 if (MaskB == 0) {
4383 ByteMask &= ~(1U << i);
4384 continue;
4385 }
4386
4387 // If the AndMask is not all ones for this byte, it's not a bytezap.
4388 if (MaskB != Byte)
4389 return true;
4390
4391 // Otherwise, this byte is kept.
4392 }
4393
4394 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4395 ByteValues);
4396 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004397 }
4398
Chris Lattner8c34cd22008-10-05 02:13:19 +00004399 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4400 // the input value to the bswap. Some observations: 1) if more than one byte
4401 // is demanded from this input, then it could not be successfully assembled
4402 // into a byteswap. At least one of the two bytes would not be aligned with
4403 // their ultimate destination.
4404 if (!isPowerOf2_32(ByteMask)) return true;
4405 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004406
Chris Lattner8c34cd22008-10-05 02:13:19 +00004407 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4408 // is demanded, it needs to go into byte 0 of the result. This means that the
4409 // byte needs to be shifted until it lands in the right byte bucket. The
4410 // shift amount depends on the position: if the byte is coming from the high
4411 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4412 // low part, it must be shifted left.
4413 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4414 if (InputByteNo < ByteValues.size()/2) {
4415 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4416 return true;
4417 } else {
4418 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4419 return true;
4420 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004421
4422 // If the destination byte value is already defined, the values are or'd
4423 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004424 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004425 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004426 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004427 return false;
4428}
4429
4430/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4431/// If so, insert the new bswap intrinsic and return it.
4432Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004433 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004434 if (!ITy || ITy->getBitWidth() % 16 ||
4435 // ByteMask only allows up to 32-byte values.
4436 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004437 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004438
4439 /// ByteValues - For each byte of the result, we keep track of which value
4440 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004441 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004442 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004443
4444 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004445 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4446 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004447 return 0;
4448
4449 // Check to see if all of the bytes come from the same value.
4450 Value *V = ByteValues[0];
4451 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4452
4453 // Check to make sure that all of the bytes come from the same value.
4454 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4455 if (ByteValues[i] != V)
4456 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004457 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004458 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004459 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004460 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004461}
4462
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004463/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4464/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4465/// we can simplify this expression to "cond ? C : D or B".
4466static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004467 Value *C, Value *D,
4468 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004469 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004470 Value *Cond = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004471 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004472 return 0;
4473
Chris Lattnera6a474d2008-11-16 04:26:55 +00004474 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004475 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004476 return SelectInst::Create(Cond, C, B);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004477 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004478 return SelectInst::Create(Cond, C, B);
4479 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004480 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004481 return SelectInst::Create(Cond, C, D);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004482 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004483 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004484 return 0;
4485}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004486
Chris Lattner69d4ced2008-11-16 05:20:07 +00004487/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4488Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4489 ICmpInst *LHS, ICmpInst *RHS) {
4490 Value *Val, *Val2;
4491 ConstantInt *LHSCst, *RHSCst;
4492 ICmpInst::Predicate LHSCC, RHSCC;
4493
4494 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004495 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4496 m_ConstantInt(LHSCst)), *Context) ||
4497 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4498 m_ConstantInt(RHSCst)), *Context))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004499 return 0;
4500
4501 // From here on, we only handle:
4502 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4503 if (Val != Val2) return 0;
4504
4505 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4506 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4507 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4508 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4509 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4510 return 0;
4511
4512 // We can't fold (ugt x, C) | (sgt x, C2).
4513 if (!PredicatesFoldable(LHSCC, RHSCC))
4514 return 0;
4515
4516 // Ensure that the larger constant is on the RHS.
4517 bool ShouldSwap;
4518 if (ICmpInst::isSignedPredicate(LHSCC) ||
4519 (ICmpInst::isEquality(LHSCC) &&
4520 ICmpInst::isSignedPredicate(RHSCC)))
4521 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4522 else
4523 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4524
4525 if (ShouldSwap) {
4526 std::swap(LHS, RHS);
4527 std::swap(LHSCst, RHSCst);
4528 std::swap(LHSCC, RHSCC);
4529 }
4530
4531 // At this point, we know we have have two icmp instructions
4532 // comparing a value against two constants and or'ing the result
4533 // together. Because of the above check, we know that we only have
4534 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4535 // FoldICmpLogical check above), that the two constants are not
4536 // equal.
4537 assert(LHSCst != RHSCst && "Compares not folded above?");
4538
4539 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004540 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004541 case ICmpInst::ICMP_EQ:
4542 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004543 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004544 case ICmpInst::ICMP_EQ:
Owen Andersond672ecb2009-07-03 00:17:18 +00004545 if (LHSCst == SubOne(RHSCst, Context)) {
4546 // (X == 13 | X == 14) -> X-13 <u 2
4547 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004548 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4549 Val->getName()+".off");
4550 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00004551 AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
Owen Anderson333c4002009-07-09 23:48:35 +00004552 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004553 }
4554 break; // (X == 13 | X == 15) -> no change
4555 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4556 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4557 break;
4558 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4559 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4560 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4561 return ReplaceInstUsesWith(I, RHS);
4562 }
4563 break;
4564 case ICmpInst::ICMP_NE:
4565 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004566 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004567 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4568 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4569 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4570 return ReplaceInstUsesWith(I, LHS);
4571 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4572 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4573 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Andersond672ecb2009-07-03 00:17:18 +00004574 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004575 }
4576 break;
4577 case ICmpInst::ICMP_ULT:
4578 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004579 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004580 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4581 break;
4582 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4583 // If RHSCst is [us]MAXINT, it is always false. Not handling
4584 // this can cause overflow.
4585 if (RHSCst->isMaxValue(false))
4586 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004587 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4588 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004589 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4590 break;
4591 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4592 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4593 return ReplaceInstUsesWith(I, RHS);
4594 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4595 break;
4596 }
4597 break;
4598 case ICmpInst::ICMP_SLT:
4599 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004600 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004601 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4602 break;
4603 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4604 // If RHSCst is [us]MAXINT, it is always false. Not handling
4605 // this can cause overflow.
4606 if (RHSCst->isMaxValue(true))
4607 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004608 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4609 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004610 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4611 break;
4612 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4613 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4614 return ReplaceInstUsesWith(I, RHS);
4615 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4616 break;
4617 }
4618 break;
4619 case ICmpInst::ICMP_UGT:
4620 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004621 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004622 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4623 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4624 return ReplaceInstUsesWith(I, LHS);
4625 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4626 break;
4627 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4628 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Andersond672ecb2009-07-03 00:17:18 +00004629 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004630 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4631 break;
4632 }
4633 break;
4634 case ICmpInst::ICMP_SGT:
4635 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004636 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004637 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4638 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4639 return ReplaceInstUsesWith(I, LHS);
4640 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4641 break;
4642 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4643 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Andersond672ecb2009-07-03 00:17:18 +00004644 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004645 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4646 break;
4647 }
4648 break;
4649 }
4650 return 0;
4651}
4652
Bill Wendlinga698a472008-12-01 08:23:25 +00004653/// FoldOrWithConstants - This helper function folds:
4654///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004655/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004656///
4657/// into:
4658///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004659/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004660///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004661/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004662Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004663 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004664 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4665 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004666
Bill Wendling286a0542008-12-02 06:24:20 +00004667 Value *V1 = 0;
4668 ConstantInt *CI2 = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004669 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004670
Bill Wendling29976b92008-12-02 06:18:11 +00004671 APInt Xor = CI1->getValue() ^ CI2->getValue();
4672 if (!Xor.isAllOnesValue()) return 0;
4673
Bill Wendling286a0542008-12-02 06:24:20 +00004674 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004675 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004676 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4677 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004678 }
4679
4680 return 0;
4681}
4682
Chris Lattner7e708292002-06-25 16:13:24 +00004683Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004684 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004685 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004686
Chris Lattner42593e62007-03-24 23:56:43 +00004687 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004688 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004689
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004690 // or X, X = X
4691 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004692 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004693
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004694 // See if we can simplify any instructions used by the instruction whose sole
4695 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004696 if (SimplifyDemandedInstructionBits(I))
4697 return &I;
4698 if (isa<VectorType>(I.getType())) {
4699 if (isa<ConstantAggregateZero>(Op1)) {
4700 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4701 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4702 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4703 return ReplaceInstUsesWith(I, I.getOperand(1));
4704 }
Chris Lattner42593e62007-03-24 23:56:43 +00004705 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004706
Chris Lattner3f5b8772002-05-06 16:14:14 +00004707 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004708 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004709 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004710 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004711 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) &&
4712 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004713 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004714 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004715 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004716 return BinaryOperator::CreateAnd(Or,
Owen Andersond672ecb2009-07-03 00:17:18 +00004717 Context->getConstantInt(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004718 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004719
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004720 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004721 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) &&
4722 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004723 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004724 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004725 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004726 return BinaryOperator::CreateXor(Or,
Owen Andersond672ecb2009-07-03 00:17:18 +00004727 Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004728 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004729
4730 // Try to fold constant and into select arguments.
4731 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004732 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004733 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004734 if (isa<PHINode>(Op0))
4735 if (Instruction *NV = FoldOpIntoPhi(I))
4736 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004737 }
4738
Chris Lattner4f637d42006-01-06 17:59:59 +00004739 Value *A = 0, *B = 0;
4740 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004741
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004742 if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004743 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4744 return ReplaceInstUsesWith(I, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004745 if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004746 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4747 return ReplaceInstUsesWith(I, Op0);
4748
Chris Lattner6423d4c2006-07-10 20:25:24 +00004749 // (A | B) | C and A | (B | C) -> bswap if possible.
4750 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004751 if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4752 match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4753 (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4754 match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004755 if (Instruction *BSwap = MatchBSwap(I))
4756 return BSwap;
4757 }
4758
Chris Lattner6e4c6492005-05-09 04:58:36 +00004759 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004760 if (Op0->hasOneUse() &&
4761 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004762 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004763 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004764 InsertNewInstBefore(NOr, I);
4765 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004766 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004767 }
4768
4769 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004770 if (Op1->hasOneUse() &&
4771 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004772 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004773 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004774 InsertNewInstBefore(NOr, I);
4775 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004776 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004777 }
4778
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004779 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004780 Value *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004781 if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4782 match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004783 Value *V1 = 0, *V2 = 0, *V3 = 0;
4784 C1 = dyn_cast<ConstantInt>(C);
4785 C2 = dyn_cast<ConstantInt>(D);
4786 if (C1 && C2) { // (A & C1)|(B & C2)
4787 // If we have: ((V + N) & C1) | (V & C2)
4788 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4789 // replace with V+N.
4790 if (C1->getValue() == ~C2->getValue()) {
4791 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004792 match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004793 // Add commutes, try both ways.
4794 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4795 return ReplaceInstUsesWith(I, A);
4796 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4797 return ReplaceInstUsesWith(I, A);
4798 }
4799 // Or commutes, try both ways.
4800 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004801 match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004802 // Add commutes, try both ways.
4803 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4804 return ReplaceInstUsesWith(I, B);
4805 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4806 return ReplaceInstUsesWith(I, B);
4807 }
4808 }
Chris Lattner044e5332007-04-08 08:01:49 +00004809 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004810 }
4811
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004812 // Check to see if we have any common things being and'ed. If so, find the
4813 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004814 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4815 if (A == B) // (A & C)|(A & D) == A & (C|D)
4816 V1 = A, V2 = C, V3 = D;
4817 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4818 V1 = A, V2 = B, V3 = C;
4819 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4820 V1 = C, V2 = A, V3 = D;
4821 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4822 V1 = C, V2 = A, V3 = B;
4823
4824 if (V1) {
4825 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004826 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4827 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004828 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004829 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004830
Dan Gohman1975d032008-10-30 20:40:10 +00004831 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004832 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004833 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004834 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004835 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004836 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004837 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004838 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004839 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004840
Bill Wendlingb01865c2008-11-30 13:52:49 +00004841 // ((A&~B)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004842 if ((match(C, m_Not(m_Specific(D)), *Context) &&
4843 match(B, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004844 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004845 // ((~B&A)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004846 if ((match(A, m_Not(m_Specific(D)), *Context) &&
4847 match(B, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004848 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004849 // ((A&~B)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004850 if ((match(C, m_Not(m_Specific(B)), *Context) &&
4851 match(D, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004852 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004853 // ((~B&A)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004854 if ((match(A, m_Not(m_Specific(B)), *Context) &&
4855 match(D, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004856 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004857 }
Chris Lattnere511b742006-11-14 07:46:50 +00004858
4859 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004860 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4861 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4862 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004863 SI0->getOperand(1) == SI1->getOperand(1) &&
4864 (SI0->hasOneUse() || SI1->hasOneUse())) {
4865 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004866 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004867 SI1->getOperand(0),
4868 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004869 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004870 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004871 }
4872 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004873
Bill Wendlingb3833d12008-12-01 01:07:11 +00004874 // ((A|B)&1)|(B&-2) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004875 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4876 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004877 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004878 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004879 }
4880 // (B&-2)|((A|B)&1) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004881 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4882 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004883 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004884 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004885 }
4886
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004887 if (match(Op0, m_Not(m_Value(A)), *Context)) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004888 if (A == Op1) // ~A | A == -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004889 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004890 } else {
4891 A = 0;
4892 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004893 // Note, A is still live here!
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004894 if (match(Op1, m_Not(m_Value(B)), *Context)) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004895 if (Op0 == B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004896 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004897
Misha Brukmancb6267b2004-07-30 12:50:08 +00004898 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004899 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004900 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004901 I.getName()+".demorgan"), I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004902 return BinaryOperator::CreateNot(*Context, And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004903 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004904 }
Chris Lattnera2881962003-02-18 19:28:33 +00004905
Reid Spencere4d87aa2006-12-23 06:05:41 +00004906 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4907 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004908 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004909 return R;
4910
Chris Lattner69d4ced2008-11-16 05:20:07 +00004911 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4912 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4913 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004914 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004915
4916 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004917 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004918 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004919 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004920 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4921 !isa<ICmpInst>(Op1C->getOperand(0))) {
4922 const Type *SrcTy = Op0C->getOperand(0)->getType();
4923 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4924 // Only do this if the casts both really cause code to be
4925 // generated.
4926 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4927 I.getType(), TD) &&
4928 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4929 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004930 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004931 Op1C->getOperand(0),
4932 I.getName());
4933 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004934 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004935 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004936 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004937 }
Chris Lattner99c65742007-10-24 05:38:08 +00004938 }
4939
4940
4941 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4942 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4943 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4944 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004945 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004946 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004947 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4948 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4949 // If either of the constants are nans, then the whole thing returns
4950 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004951 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersond672ecb2009-07-03 00:17:18 +00004952 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner99c65742007-10-24 05:38:08 +00004953
4954 // Otherwise, no need to compare the two constants, compare the
4955 // rest.
Owen Anderson333c4002009-07-09 23:48:35 +00004956 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4957 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner99c65742007-10-24 05:38:08 +00004958 }
Evan Cheng40300622008-10-14 18:44:08 +00004959 } else {
4960 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4961 FCmpInst::Predicate Op0CC, Op1CC;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004962 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4963 m_Value(Op0RHS)), *Context) &&
4964 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4965 m_Value(Op1RHS)), *Context)) {
Evan Cheng40300622008-10-14 18:44:08 +00004966 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4967 // Swap RHS operands to match LHS.
4968 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4969 std::swap(Op1LHS, Op1RHS);
4970 }
4971 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4972 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4973 if (Op0CC == Op1CC)
Owen Anderson333c4002009-07-09 23:48:35 +00004974 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4975 Op0LHS, Op0RHS);
Evan Cheng40300622008-10-14 18:44:08 +00004976 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4977 Op1CC == FCmpInst::FCMP_TRUE)
Owen Andersond672ecb2009-07-03 00:17:18 +00004978 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng40300622008-10-14 18:44:08 +00004979 else if (Op0CC == FCmpInst::FCMP_FALSE)
4980 return ReplaceInstUsesWith(I, Op1);
4981 else if (Op1CC == FCmpInst::FCMP_FALSE)
4982 return ReplaceInstUsesWith(I, Op0);
4983 bool Op0Ordered;
4984 bool Op1Ordered;
4985 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4986 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4987 if (Op0Ordered == Op1Ordered) {
4988 // If both are ordered or unordered, return a new fcmp with
4989 // or'ed predicates.
4990 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
Owen Andersond672ecb2009-07-03 00:17:18 +00004991 Op0LHS, Op0RHS, Context);
Evan Cheng40300622008-10-14 18:44:08 +00004992 if (Instruction *I = dyn_cast<Instruction>(RV))
4993 return I;
4994 // Otherwise, it's a constant boolean value...
4995 return ReplaceInstUsesWith(I, RV);
4996 }
4997 }
4998 }
4999 }
Chris Lattner99c65742007-10-24 05:38:08 +00005000 }
5001 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005002
Chris Lattner7e708292002-06-25 16:13:24 +00005003 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005004}
5005
Dan Gohman844731a2008-05-13 00:00:25 +00005006namespace {
5007
Chris Lattnerc317d392004-02-16 01:20:27 +00005008// XorSelf - Implements: X ^ X --> 0
5009struct XorSelf {
5010 Value *RHS;
5011 XorSelf(Value *rhs) : RHS(rhs) {}
5012 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5013 Instruction *apply(BinaryOperator &Xor) const {
5014 return &Xor;
5015 }
5016};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005017
Dan Gohman844731a2008-05-13 00:00:25 +00005018}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005019
Chris Lattner7e708292002-06-25 16:13:24 +00005020Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005021 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005022 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005023
Evan Chengd34af782008-03-25 20:07:13 +00005024 if (isa<UndefValue>(Op1)) {
5025 if (isa<UndefValue>(Op0))
5026 // Handle undef ^ undef -> 0 special case. This is a common
5027 // idiom (misuse).
Owen Andersond672ecb2009-07-03 00:17:18 +00005028 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005029 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005030 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005031
Chris Lattnerc317d392004-02-16 01:20:27 +00005032 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Owen Andersond672ecb2009-07-03 00:17:18 +00005033 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005034 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersond672ecb2009-07-03 00:17:18 +00005035 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005036 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005037
5038 // See if we can simplify any instructions used by the instruction whose sole
5039 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005040 if (SimplifyDemandedInstructionBits(I))
5041 return &I;
5042 if (isa<VectorType>(I.getType()))
5043 if (isa<ConstantAggregateZero>(Op1))
5044 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005045
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005046 // Is this a ~ operation?
Owen Andersond672ecb2009-07-03 00:17:18 +00005047 if (Value *NotOp = dyn_castNotVal(&I, Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005048 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5049 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5050 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5051 if (Op0I->getOpcode() == Instruction::And ||
5052 Op0I->getOpcode() == Instruction::Or) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005053 if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5054 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005055 Instruction *NotY =
Owen Anderson73c6b712009-07-13 20:58:05 +00005056 BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005057 Op0I->getOperand(1)->getName()+".not");
5058 InsertNewInstBefore(NotY, I);
5059 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005060 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005061 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005062 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005063 }
5064 }
5065 }
5066 }
5067
5068
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005069 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005070 if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005071 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005072 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005073 return new ICmpInst(*Context, ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005074 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005075
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005076 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005077 return new FCmpInst(*Context, FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005078 FCI->getOperand(0), FCI->getOperand(1));
5079 }
5080
Nick Lewycky517e1f52008-05-31 19:01:33 +00005081 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5082 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5083 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5084 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5085 Instruction::CastOps Opcode = Op0C->getOpcode();
5086 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005087 if (RHS == Context->getConstantExprCast(Opcode,
5088 Context->getConstantIntTrue(),
Nick Lewycky517e1f52008-05-31 19:01:33 +00005089 Op0C->getDestTy())) {
5090 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
Owen Anderson333c4002009-07-09 23:48:35 +00005091 *Context,
Nick Lewycky517e1f52008-05-31 19:01:33 +00005092 CI->getOpcode(), CI->getInversePredicate(),
5093 CI->getOperand(0), CI->getOperand(1)), I);
5094 NewCI->takeName(CI);
5095 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5096 }
5097 }
5098 }
5099 }
5100 }
5101
Reid Spencere4d87aa2006-12-23 06:05:41 +00005102 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005103 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005104 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5105 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005106 Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5107 Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5108 Context->getConstantInt(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005109 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005110 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005111
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005112 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005113 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005114 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005115 if (RHS->isAllOnesValue()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005116 Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005117 return BinaryOperator::CreateSub(
Owen Andersond672ecb2009-07-03 00:17:18 +00005118 Context->getConstantExprSub(NegOp0CI,
5119 Context->getConstantInt(I.getType(), 1)),
5120 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005121 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005122 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersond672ecb2009-07-03 00:17:18 +00005123 Constant *C =
5124 Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005125 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005126
Chris Lattner7c4049c2004-01-12 19:35:11 +00005127 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005128 } else if (Op0I->getOpcode() == Instruction::Or) {
5129 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005130 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005131 Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005132 // Anything in both C1 and C2 is known to be zero, remove it from
5133 // NewRHS.
Owen Andersond672ecb2009-07-03 00:17:18 +00005134 Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5135 NewRHS = Context->getConstantExprAnd(NewRHS,
5136 Context->getConstantExprNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005137 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005138 I.setOperand(0, Op0I->getOperand(0));
5139 I.setOperand(1, NewRHS);
5140 return &I;
5141 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005142 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005143 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005144 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005145
5146 // Try to fold constant and into select arguments.
5147 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005148 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005149 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005150 if (isa<PHINode>(Op0))
5151 if (Instruction *NV = FoldOpIntoPhi(I))
5152 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005153 }
5154
Owen Andersond672ecb2009-07-03 00:17:18 +00005155 if (Value *X = dyn_castNotVal(Op0, Context)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005156 if (X == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005157 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005158
Owen Andersond672ecb2009-07-03 00:17:18 +00005159 if (Value *X = dyn_castNotVal(Op1, Context)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005160 if (X == Op0)
Owen Andersond672ecb2009-07-03 00:17:18 +00005161 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005162
Chris Lattner318bf792007-03-18 22:51:34 +00005163
5164 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5165 if (Op1I) {
5166 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005167 if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005168 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005169 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005170 I.swapOperands();
5171 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005172 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005173 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005174 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005175 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005176 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005177 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005178 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005179 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005180 } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) &&
5181 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005182 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005183 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005184 std::swap(A, B);
5185 }
Chris Lattner318bf792007-03-18 22:51:34 +00005186 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005187 I.swapOperands(); // Simplified below.
5188 std::swap(Op0, Op1);
5189 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005190 }
Chris Lattner318bf792007-03-18 22:51:34 +00005191 }
5192
5193 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5194 if (Op0I) {
5195 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005196 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5197 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005198 if (A == Op1) // (B|A)^B == (A|B)^B
5199 std::swap(A, B);
5200 if (B == Op1) { // (A|B)^B == A & ~B
5201 Instruction *NotB =
Owen Anderson73c6b712009-07-13 20:58:05 +00005202 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
5203 Op1, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005204 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005205 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005206 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005207 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005208 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005209 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005210 } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5211 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005212 if (A == Op1) // (A&B)^A -> (B&A)^A
5213 std::swap(A, B);
5214 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005215 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005216 Instruction *N =
Owen Anderson73c6b712009-07-13 20:58:05 +00005217 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005218 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005219 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005220 }
Chris Lattner318bf792007-03-18 22:51:34 +00005221 }
5222
5223 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5224 if (Op0I && Op1I && Op0I->isShift() &&
5225 Op0I->getOpcode() == Op1I->getOpcode() &&
5226 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5227 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5228 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005229 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005230 Op1I->getOperand(0),
5231 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005232 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005233 Op1I->getOperand(1));
5234 }
5235
5236 if (Op0I && Op1I) {
5237 Value *A, *B, *C, *D;
5238 // (A & B)^(A | B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005239 if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5240 match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005241 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005242 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005243 }
5244 // (A | B)^(A & B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005245 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5246 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005247 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005248 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005249 }
5250
5251 // (A & B)^(C & D)
5252 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005253 match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5254 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005255 // (X & Y)^(X & Y) -> (Y^Z) & X
5256 Value *X = 0, *Y = 0, *Z = 0;
5257 if (A == C)
5258 X = A, Y = B, Z = D;
5259 else if (A == D)
5260 X = A, Y = B, Z = C;
5261 else if (B == C)
5262 X = B, Y = A, Z = D;
5263 else if (B == D)
5264 X = B, Y = A, Z = C;
5265
5266 if (X) {
5267 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005268 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5269 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005270 }
5271 }
5272 }
5273
Reid Spencere4d87aa2006-12-23 06:05:41 +00005274 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5275 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005276 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005277 return R;
5278
Chris Lattner6fc205f2006-05-05 06:39:07 +00005279 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005280 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005281 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005282 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5283 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005284 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005285 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005286 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5287 I.getType(), TD) &&
5288 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5289 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005290 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005291 Op1C->getOperand(0),
5292 I.getName());
5293 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005294 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005295 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005296 }
Chris Lattner99c65742007-10-24 05:38:08 +00005297 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005298
Chris Lattner7e708292002-06-25 16:13:24 +00005299 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005300}
5301
Owen Andersond672ecb2009-07-03 00:17:18 +00005302static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005303 LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005304 return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005305}
Chris Lattnera96879a2004-09-29 17:40:11 +00005306
Dan Gohman6de29f82009-06-15 22:12:54 +00005307static bool HasAddOverflow(ConstantInt *Result,
5308 ConstantInt *In1, ConstantInt *In2,
5309 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005310 if (IsSigned)
5311 if (In2->getValue().isNegative())
5312 return Result->getValue().sgt(In1->getValue());
5313 else
5314 return Result->getValue().slt(In1->getValue());
5315 else
5316 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005317}
5318
Dan Gohman6de29f82009-06-15 22:12:54 +00005319/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005320/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005321static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005322 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005323 bool IsSigned = false) {
5324 Result = Context->getConstantExprAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005325
Dan Gohman6de29f82009-06-15 22:12:54 +00005326 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5327 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005328 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5329 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5330 ExtractElement(In1, Idx, Context),
5331 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005332 IsSigned))
5333 return true;
5334 }
5335 return false;
5336 }
5337
5338 return HasAddOverflow(cast<ConstantInt>(Result),
5339 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5340 IsSigned);
5341}
5342
5343static bool HasSubOverflow(ConstantInt *Result,
5344 ConstantInt *In1, ConstantInt *In2,
5345 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005346 if (IsSigned)
5347 if (In2->getValue().isNegative())
5348 return Result->getValue().slt(In1->getValue());
5349 else
5350 return Result->getValue().sgt(In1->getValue());
5351 else
5352 return Result->getValue().ugt(In1->getValue());
5353}
5354
Dan Gohman6de29f82009-06-15 22:12:54 +00005355/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5356/// overflowed for this type.
5357static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005358 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005359 bool IsSigned = false) {
5360 Result = Context->getConstantExprSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005361
5362 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5363 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005364 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5365 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5366 ExtractElement(In1, Idx, Context),
5367 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005368 IsSigned))
5369 return true;
5370 }
5371 return false;
5372 }
5373
5374 return HasSubOverflow(cast<ConstantInt>(Result),
5375 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5376 IsSigned);
5377}
5378
Chris Lattner574da9b2005-01-13 20:14:25 +00005379/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5380/// code necessary to compute the offset from the base pointer (without adding
5381/// in the base pointer). Return the result as a signed integer of intptr size.
5382static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5383 TargetData &TD = IC.getTargetData();
5384 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005385 const Type *IntPtrTy = TD.getIntPtrType();
Owen Anderson07cf79e2009-07-06 23:00:19 +00005386 LLVMContext *Context = IC.getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00005387 Value *Result = Context->getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005388
5389 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005390 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005391 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005392
Gabor Greif177dd3f2008-06-12 21:37:33 +00005393 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5394 ++i, ++GTI) {
5395 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005396 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005397 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5398 if (OpC->isZero()) continue;
5399
5400 // Handle a struct index, which adds its field offset to the pointer.
5401 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5402 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5403
5404 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005405 Result =
5406 Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005407 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005408 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005409 BinaryOperator::CreateAdd(Result,
Owen Andersond672ecb2009-07-03 00:17:18 +00005410 Context->getConstantInt(IntPtrTy, Size),
Chris Lattnere62f0212007-04-28 04:52:43 +00005411 GEP->getName()+".offs"), I);
5412 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005413 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005414
Owen Andersond672ecb2009-07-03 00:17:18 +00005415 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5416 Constant *OC =
5417 Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5418 Scale = Context->getConstantExprMul(OC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005419 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005420 Result = Context->getConstantExprAdd(RC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005421 else {
5422 // Emit an add instruction.
5423 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005424 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005425 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005426 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005427 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005428 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005429 // Convert to correct type.
5430 if (Op->getType() != IntPtrTy) {
5431 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005432 Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005433 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005434 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5435 true,
5436 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005437 }
5438 if (Size != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005439 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
Chris Lattnere62f0212007-04-28 04:52:43 +00005440 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005441 Op = Context->getConstantExprMul(OpC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005442 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005443 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005444 GEP->getName()+".idx"), I);
5445 }
5446
5447 // Emit an add instruction.
5448 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005449 Result = Context->getConstantExprAdd(cast<Constant>(Op),
Chris Lattnere62f0212007-04-28 04:52:43 +00005450 cast<Constant>(Result));
5451 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005452 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005453 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005454 }
5455 return Result;
5456}
5457
Chris Lattner10c0d912008-04-22 02:53:33 +00005458
5459/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5460/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5461/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5462/// complex, and scales are involved. The above expression would also be legal
5463/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5464/// later form is less amenable to optimization though, and we are allowed to
5465/// generate the first by knowing that pointer arithmetic doesn't overflow.
5466///
5467/// If we can't emit an optimized form for this expression, this returns null.
5468///
5469static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5470 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005471 TargetData &TD = IC.getTargetData();
5472 gep_type_iterator GTI = gep_type_begin(GEP);
5473
5474 // Check to see if this gep only has a single variable index. If so, and if
5475 // any constant indices are a multiple of its scale, then we can compute this
5476 // in terms of the scale of the variable index. For example, if the GEP
5477 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5478 // because the expression will cross zero at the same point.
5479 unsigned i, e = GEP->getNumOperands();
5480 int64_t Offset = 0;
5481 for (i = 1; i != e; ++i, ++GTI) {
5482 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5483 // Compute the aggregate offset of constant indices.
5484 if (CI->isZero()) continue;
5485
5486 // Handle a struct index, which adds its field offset to the pointer.
5487 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5488 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5489 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005490 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005491 Offset += Size*CI->getSExtValue();
5492 }
5493 } else {
5494 // Found our variable index.
5495 break;
5496 }
5497 }
5498
5499 // If there are no variable indices, we must have a constant offset, just
5500 // evaluate it the general way.
5501 if (i == e) return 0;
5502
5503 Value *VariableIdx = GEP->getOperand(i);
5504 // Determine the scale factor of the variable element. For example, this is
5505 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005506 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005507
5508 // Verify that there are no other variable indices. If so, emit the hard way.
5509 for (++i, ++GTI; i != e; ++i, ++GTI) {
5510 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5511 if (!CI) return 0;
5512
5513 // Compute the aggregate offset of constant indices.
5514 if (CI->isZero()) continue;
5515
5516 // Handle a struct index, which adds its field offset to the pointer.
5517 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5518 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5519 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005520 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005521 Offset += Size*CI->getSExtValue();
5522 }
5523 }
5524
5525 // Okay, we know we have a single variable index, which must be a
5526 // pointer/array/vector index. If there is no offset, life is simple, return
5527 // the index.
5528 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5529 if (Offset == 0) {
5530 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5531 // we don't need to bother extending: the extension won't affect where the
5532 // computation crosses zero.
5533 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5534 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5535 VariableIdx->getNameStart(), &I);
5536 return VariableIdx;
5537 }
5538
5539 // Otherwise, there is an index. The computation we will do will be modulo
5540 // the pointer size, so get it.
5541 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5542
5543 Offset &= PtrSizeMask;
5544 VariableScale &= PtrSizeMask;
5545
5546 // To do this transformation, any constant index must be a multiple of the
5547 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5548 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5549 // multiple of the variable scale.
5550 int64_t NewOffs = Offset / (int64_t)VariableScale;
5551 if (Offset != NewOffs*(int64_t)VariableScale)
5552 return 0;
5553
5554 // Okay, we can do this evaluation. Start by converting the index to intptr.
5555 const Type *IntPtrTy = TD.getIntPtrType();
5556 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005557 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005558 true /*SExt*/,
5559 VariableIdx->getNameStart(), &I);
Owen Andersond672ecb2009-07-03 00:17:18 +00005560 Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005561 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005562}
5563
5564
Reid Spencere4d87aa2006-12-23 06:05:41 +00005565/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005566/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005567Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5568 ICmpInst::Predicate Cond,
5569 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005570 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005571
Chris Lattner10c0d912008-04-22 02:53:33 +00005572 // Look through bitcasts.
5573 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5574 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005575
Chris Lattner574da9b2005-01-13 20:14:25 +00005576 Value *PtrBase = GEPLHS->getOperand(0);
5577 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005578 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005579 // This transformation (ignoring the base and scales) is valid because we
5580 // know pointers can't overflow. See if we can output an optimized form.
5581 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5582
5583 // If not, synthesize the offset the hard way.
5584 if (Offset == 0)
5585 Offset = EmitGEPOffset(GEPLHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005586 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersond672ecb2009-07-03 00:17:18 +00005587 Context->getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005588 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005589 // If the base pointers are different, but the indices are the same, just
5590 // compare the base pointer.
5591 if (PtrBase != GEPRHS->getOperand(0)) {
5592 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005593 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005594 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005595 if (IndicesTheSame)
5596 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5597 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5598 IndicesTheSame = false;
5599 break;
5600 }
5601
5602 // If all indices are the same, just compare the base pointers.
5603 if (IndicesTheSame)
Owen Anderson333c4002009-07-09 23:48:35 +00005604 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005605 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005606
5607 // Otherwise, the base pointers are different and the indices are
5608 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005609 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005610 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005611
Chris Lattnere9d782b2005-01-13 22:25:21 +00005612 // If one of the GEPs has all zero indices, recurse.
5613 bool AllZeros = true;
5614 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5615 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5616 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5617 AllZeros = false;
5618 break;
5619 }
5620 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005621 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5622 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005623
5624 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005625 AllZeros = true;
5626 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5627 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5628 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5629 AllZeros = false;
5630 break;
5631 }
5632 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005633 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005634
Chris Lattner4401c9c2005-01-14 00:20:05 +00005635 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5636 // If the GEPs only differ by one index, compare it.
5637 unsigned NumDifferences = 0; // Keep track of # differences.
5638 unsigned DiffOperand = 0; // The operand that differs.
5639 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5640 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005641 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5642 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005643 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005644 NumDifferences = 2;
5645 break;
5646 } else {
5647 if (NumDifferences++) break;
5648 DiffOperand = i;
5649 }
5650 }
5651
5652 if (NumDifferences == 0) // SAME GEP?
5653 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Andersond672ecb2009-07-03 00:17:18 +00005654 Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005655 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005656
Chris Lattner4401c9c2005-01-14 00:20:05 +00005657 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005658 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5659 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005660 // Make sure we do a signed comparison here.
Owen Anderson333c4002009-07-09 23:48:35 +00005661 return new ICmpInst(*Context,
5662 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005663 }
5664 }
5665
Reid Spencere4d87aa2006-12-23 06:05:41 +00005666 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005667 // the result to fold to a constant!
5668 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5669 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5670 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5671 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5672 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005673 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005674 }
5675 }
5676 return 0;
5677}
5678
Chris Lattnera5406232008-05-19 20:18:56 +00005679/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5680///
5681Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5682 Instruction *LHSI,
5683 Constant *RHSC) {
5684 if (!isa<ConstantFP>(RHSC)) return 0;
5685 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5686
5687 // Get the width of the mantissa. We don't want to hack on conversions that
5688 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005689 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005690 if (MantissaWidth == -1) return 0; // Unknown.
5691
5692 // Check to see that the input is converted from an integer type that is small
5693 // enough that preserves all bits. TODO: check here for "known" sign bits.
5694 // 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 +00005695 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005696
5697 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005698 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5699 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005700 ++InputSize;
5701
5702 // If the conversion would lose info, don't hack on this.
5703 if ((int)InputSize > MantissaWidth)
5704 return 0;
5705
5706 // Otherwise, we can potentially simplify the comparison. We know that it
5707 // will always come through as an integer value and we know the constant is
5708 // not a NAN (it would have been previously simplified).
5709 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5710
5711 ICmpInst::Predicate Pred;
5712 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005713 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005714 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005715 case FCmpInst::FCMP_OEQ:
5716 Pred = ICmpInst::ICMP_EQ;
5717 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005718 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005719 case FCmpInst::FCMP_OGT:
5720 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5721 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005722 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005723 case FCmpInst::FCMP_OGE:
5724 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5725 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005726 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005727 case FCmpInst::FCMP_OLT:
5728 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5729 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005730 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005731 case FCmpInst::FCMP_OLE:
5732 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5733 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005734 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005735 case FCmpInst::FCMP_ONE:
5736 Pred = ICmpInst::ICMP_NE;
5737 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005738 case FCmpInst::FCMP_ORD:
Owen Andersond672ecb2009-07-03 00:17:18 +00005739 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005740 case FCmpInst::FCMP_UNO:
Owen Andersond672ecb2009-07-03 00:17:18 +00005741 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005742 }
5743
5744 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5745
5746 // Now we know that the APFloat is a normal number, zero or inf.
5747
Chris Lattner85162782008-05-20 03:50:52 +00005748 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005749 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005750 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005751
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005752 if (!LHSUnsigned) {
5753 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5754 // and large values.
5755 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5756 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5757 APFloat::rmNearestTiesToEven);
5758 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5759 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5760 Pred == ICmpInst::ICMP_SLE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005761 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5762 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005763 }
5764 } else {
5765 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5766 // +INF and large values.
5767 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5768 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5769 APFloat::rmNearestTiesToEven);
5770 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5771 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5772 Pred == ICmpInst::ICMP_ULE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005773 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5774 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005775 }
Chris Lattnera5406232008-05-19 20:18:56 +00005776 }
5777
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005778 if (!LHSUnsigned) {
5779 // See if the RHS value is < SignedMin.
5780 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5781 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5782 APFloat::rmNearestTiesToEven);
5783 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5784 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5785 Pred == ICmpInst::ICMP_SGE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005786 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5787 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005788 }
Chris Lattnera5406232008-05-19 20:18:56 +00005789 }
5790
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005791 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5792 // [0, UMAX], but it may still be fractional. See if it is fractional by
5793 // casting the FP value to the integer value and back, checking for equality.
5794 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005795 Constant *RHSInt = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005796 ? Context->getConstantExprFPToUI(RHSC, IntTy)
5797 : Context->getConstantExprFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005798 if (!RHS.isZero()) {
5799 bool Equal = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005800 ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5801 : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005802 if (!Equal) {
5803 // If we had a comparison against a fractional value, we have to adjust
5804 // the compare predicate and sometimes the value. RHSC is rounded towards
5805 // zero at this point.
5806 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005807 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005808 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Andersond672ecb2009-07-03 00:17:18 +00005809 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005810 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Andersond672ecb2009-07-03 00:17:18 +00005811 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005812 case ICmpInst::ICMP_ULE:
5813 // (float)int <= 4.4 --> int <= 4
5814 // (float)int <= -4.4 --> false
5815 if (RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005816 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005817 break;
5818 case ICmpInst::ICMP_SLE:
5819 // (float)int <= 4.4 --> int <= 4
5820 // (float)int <= -4.4 --> int < -4
5821 if (RHS.isNegative())
5822 Pred = ICmpInst::ICMP_SLT;
5823 break;
5824 case ICmpInst::ICMP_ULT:
5825 // (float)int < -4.4 --> false
5826 // (float)int < 4.4 --> int <= 4
5827 if (RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005828 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005829 Pred = ICmpInst::ICMP_ULE;
5830 break;
5831 case ICmpInst::ICMP_SLT:
5832 // (float)int < -4.4 --> int < -4
5833 // (float)int < 4.4 --> int <= 4
5834 if (!RHS.isNegative())
5835 Pred = ICmpInst::ICMP_SLE;
5836 break;
5837 case ICmpInst::ICMP_UGT:
5838 // (float)int > 4.4 --> int > 4
5839 // (float)int > -4.4 --> true
5840 if (RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005841 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005842 break;
5843 case ICmpInst::ICMP_SGT:
5844 // (float)int > 4.4 --> int > 4
5845 // (float)int > -4.4 --> int >= -4
5846 if (RHS.isNegative())
5847 Pred = ICmpInst::ICMP_SGE;
5848 break;
5849 case ICmpInst::ICMP_UGE:
5850 // (float)int >= -4.4 --> true
5851 // (float)int >= 4.4 --> int > 4
5852 if (!RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005853 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005854 Pred = ICmpInst::ICMP_UGT;
5855 break;
5856 case ICmpInst::ICMP_SGE:
5857 // (float)int >= -4.4 --> int >= -4
5858 // (float)int >= 4.4 --> int > 4
5859 if (!RHS.isNegative())
5860 Pred = ICmpInst::ICMP_SGT;
5861 break;
5862 }
Chris Lattnera5406232008-05-19 20:18:56 +00005863 }
5864 }
5865
5866 // Lower this FP comparison into an appropriate integer version of the
5867 // comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00005868 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005869}
5870
Reid Spencere4d87aa2006-12-23 06:05:41 +00005871Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5872 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005873 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005874
Chris Lattner58e97462007-01-14 19:42:17 +00005875 // Fold trivial predicates.
5876 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005877 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005878 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005879 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005880
5881 // Simplify 'fcmp pred X, X'
5882 if (Op0 == Op1) {
5883 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005884 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005885 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5886 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5887 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Andersond672ecb2009-07-03 00:17:18 +00005888 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005889 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5890 case FCmpInst::FCMP_OLT: // True if ordered and less than
5891 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Andersond672ecb2009-07-03 00:17:18 +00005892 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005893
5894 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5895 case FCmpInst::FCMP_ULT: // True if unordered or less than
5896 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5897 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5898 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5899 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersond672ecb2009-07-03 00:17:18 +00005900 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005901 return &I;
5902
5903 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5904 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5905 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5906 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5907 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5908 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersond672ecb2009-07-03 00:17:18 +00005909 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005910 return &I;
5911 }
5912 }
5913
Reid Spencere4d87aa2006-12-23 06:05:41 +00005914 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005915 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005916
Reid Spencere4d87aa2006-12-23 06:05:41 +00005917 // Handle fcmp with constant RHS
5918 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005919 // If the constant is a nan, see if we can fold the comparison based on it.
5920 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5921 if (CFP->getValueAPF().isNaN()) {
5922 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Andersond672ecb2009-07-03 00:17:18 +00005923 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005924 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5925 "Comparison must be either ordered or unordered!");
5926 // True if unordered.
Owen Andersond672ecb2009-07-03 00:17:18 +00005927 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005928 }
5929 }
5930
Reid Spencere4d87aa2006-12-23 06:05:41 +00005931 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5932 switch (LHSI->getOpcode()) {
5933 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005934 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5935 // block. If in the same block, we're encouraging jump threading. If
5936 // not, we are just pessimizing the code by making an i1 phi.
5937 if (LHSI->getParent() == I.getParent())
5938 if (Instruction *NV = FoldOpIntoPhi(I))
5939 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005940 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005941 case Instruction::SIToFP:
5942 case Instruction::UIToFP:
5943 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5944 return NV;
5945 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005946 case Instruction::Select:
5947 // If either operand of the select is a constant, we can fold the
5948 // comparison into the select arms, which will cause one to be
5949 // constant folded and the select turned into a bitwise or.
5950 Value *Op1 = 0, *Op2 = 0;
5951 if (LHSI->hasOneUse()) {
5952 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5953 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005954 Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005955 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005956 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005957 LHSI->getOperand(2), RHSC,
5958 I.getName()), I);
5959 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5960 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005961 Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005962 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005963 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005964 LHSI->getOperand(1), RHSC,
5965 I.getName()), I);
5966 }
5967 }
5968
5969 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005970 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005971 break;
5972 }
5973 }
5974
5975 return Changed ? &I : 0;
5976}
5977
5978Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5979 bool Changed = SimplifyCompare(I);
5980 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5981 const Type *Ty = Op0->getType();
5982
5983 // icmp X, X
5984 if (Op0 == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005985 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005986 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005987
5988 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005989 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005990
Reid Spencere4d87aa2006-12-23 06:05:41 +00005991 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005992 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005993 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5994 isa<ConstantPointerNull>(Op0)) &&
5995 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005996 isa<ConstantPointerNull>(Op1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005997 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005998 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005999
Reid Spencere4d87aa2006-12-23 06:05:41 +00006000 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00006001 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006002 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006003 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006004 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006005 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00006006 InsertNewInstBefore(Xor, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00006007 return BinaryOperator::CreateNot(*Context, Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006008 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006009 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006010 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006011
Reid Spencere4d87aa2006-12-23 06:05:41 +00006012 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006013 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006014 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006015 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Owen Anderson73c6b712009-07-13 20:58:05 +00006016 Instruction *Not = BinaryOperator::CreateNot(*Context,
6017 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006018 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006019 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006020 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006021 case ICmpInst::ICMP_SGT:
6022 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006023 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006024 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00006025 Instruction *Not = BinaryOperator::CreateNot(*Context,
6026 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006027 InsertNewInstBefore(Not, I);
6028 return BinaryOperator::CreateAnd(Not, Op0);
6029 }
6030 case ICmpInst::ICMP_UGE:
6031 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6032 // FALL THROUGH
6033 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Owen Anderson73c6b712009-07-13 20:58:05 +00006034 Instruction *Not = BinaryOperator::CreateNot(*Context,
6035 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006036 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006037 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006038 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006039 case ICmpInst::ICMP_SGE:
6040 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6041 // FALL THROUGH
6042 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00006043 Instruction *Not = BinaryOperator::CreateNot(*Context,
6044 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006045 InsertNewInstBefore(Not, I);
6046 return BinaryOperator::CreateOr(Not, Op0);
6047 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006048 }
Chris Lattner8b170942002-08-09 23:47:40 +00006049 }
6050
Dan Gohman1c8491e2009-04-25 17:12:48 +00006051 unsigned BitWidth = 0;
6052 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006053 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6054 else if (Ty->isIntOrIntVector())
6055 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006056
6057 bool isSignBit = false;
6058
Dan Gohman81b28ce2008-09-16 18:46:06 +00006059 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006060 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006061 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006062
Chris Lattnerb6566012008-01-05 01:18:20 +00006063 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6064 if (I.isEquality() && CI->isNullValue() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006065 match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006066 // (icmp cond A B) if cond is equality
Owen Anderson333c4002009-07-09 23:48:35 +00006067 return new ICmpInst(*Context, I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006068 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006069
Dan Gohman81b28ce2008-09-16 18:46:06 +00006070 // If we have an icmp le or icmp ge instruction, turn it into the
6071 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6072 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006073 switch (I.getPredicate()) {
6074 default: break;
6075 case ICmpInst::ICMP_ULE:
6076 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006077 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006078 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6079 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006080 case ICmpInst::ICMP_SLE:
6081 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006082 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006083 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6084 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006085 case ICmpInst::ICMP_UGE:
6086 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006087 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006088 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6089 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006090 case ICmpInst::ICMP_SGE:
6091 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006092 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006093 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6094 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006095 }
6096
Chris Lattner183661e2008-07-11 05:40:05 +00006097 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006098 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006099 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006100 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6101 }
6102
6103 // See if we can fold the comparison based on range information we can get
6104 // by checking whether bits are known to be zero or one in the input.
6105 if (BitWidth != 0) {
6106 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6107 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6108
6109 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006110 isSignBit ? APInt::getSignBit(BitWidth)
6111 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006112 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006113 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006114 if (SimplifyDemandedBits(I.getOperandUse(1),
6115 APInt::getAllOnesValue(BitWidth),
6116 Op1KnownZero, Op1KnownOne, 0))
6117 return &I;
6118
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006119 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006120 // in. Compute the Min, Max and RHS values based on the known bits. For the
6121 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006122 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6123 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6124 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6125 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6126 Op0Min, Op0Max);
6127 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6128 Op1Min, Op1Max);
6129 } else {
6130 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6131 Op0Min, Op0Max);
6132 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6133 Op1Min, Op1Max);
6134 }
6135
Chris Lattner183661e2008-07-11 05:40:05 +00006136 // If Min and Max are known to be the same, then SimplifyDemandedBits
6137 // figured out that the LHS is a constant. Just constant fold this now so
6138 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006139 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006140 return new ICmpInst(*Context, I.getPredicate(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006141 Context->getConstantInt(Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006142 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006143 return new ICmpInst(*Context, I.getPredicate(), Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006144 Context->getConstantInt(Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006145
Chris Lattner183661e2008-07-11 05:40:05 +00006146 // Based on the range information we know about the LHS, see if we can
6147 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006148 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006149 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006150 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006151 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersond672ecb2009-07-03 00:17:18 +00006152 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006153 break;
6154 case ICmpInst::ICMP_NE:
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->getConstantIntTrue());
Chris Lattner84dff672008-07-11 05:08:55 +00006157 break;
6158 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006159 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006160 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006161 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006162 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006163 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006164 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006165 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6166 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006167 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6168 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006169
6170 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6171 if (CI->isMinValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006172 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Owen Anderson73c6b712009-07-13 20:58:05 +00006173 Context->getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006174 }
Chris Lattner84dff672008-07-11 05:08:55 +00006175 break;
6176 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006177 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006178 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006179 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006180 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006181
6182 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006183 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006184 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6185 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006186 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6187 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006188
6189 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6190 if (CI->isMaxValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006191 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006192 Context->getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006193 }
Chris Lattner84dff672008-07-11 05:08:55 +00006194 break;
6195 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006196 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Andersond672ecb2009-07-03 00:17:18 +00006197 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006198 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Andersond672ecb2009-07-03 00:17:18 +00006199 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006200 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006201 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006202 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6203 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006204 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6205 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006206 }
Chris Lattner84dff672008-07-11 05:08:55 +00006207 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006208 case ICmpInst::ICMP_SGT:
6209 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006210 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006211 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006212 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006213
6214 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006215 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006216 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6217 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006218 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6219 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006220 }
6221 break;
6222 case ICmpInst::ICMP_SGE:
6223 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6224 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006225 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006226 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006227 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006228 break;
6229 case ICmpInst::ICMP_SLE:
6230 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6231 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006232 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006233 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006234 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006235 break;
6236 case ICmpInst::ICMP_UGE:
6237 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6238 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006239 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006240 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006241 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006242 break;
6243 case ICmpInst::ICMP_ULE:
6244 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6245 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006246 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006247 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006248 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006249 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006250 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006251
6252 // Turn a signed comparison into an unsigned one if both operands
6253 // are known to have the same sign.
6254 if (I.isSignedPredicate() &&
6255 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6256 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Owen Anderson333c4002009-07-09 23:48:35 +00006257 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006258 }
6259
6260 // Test if the ICmpInst instruction is used exclusively by a select as
6261 // part of a minimum or maximum operation. If so, refrain from doing
6262 // any other folding. This helps out other analyses which understand
6263 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6264 // and CodeGen. And in this case, at least one of the comparison
6265 // operands has at least one user besides the compare (the select),
6266 // which would often largely negate the benefit of folding anyway.
6267 if (I.hasOneUse())
6268 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6269 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6270 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6271 return 0;
6272
6273 // See if we are doing a comparison between a constant and an instruction that
6274 // can be folded into the comparison.
6275 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006276 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006277 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006278 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006279 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006280 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6281 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006282 }
6283
Chris Lattner01deb9d2007-04-03 17:43:25 +00006284 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006285 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6286 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6287 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006288 case Instruction::GetElementPtr:
6289 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006290 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006291 bool isAllZeros = true;
6292 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6293 if (!isa<Constant>(LHSI->getOperand(i)) ||
6294 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6295 isAllZeros = false;
6296 break;
6297 }
6298 if (isAllZeros)
Owen Anderson333c4002009-07-09 23:48:35 +00006299 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006300 Context->getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006301 }
6302 break;
6303
Chris Lattner6970b662005-04-23 15:31:55 +00006304 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006305 // Only fold icmp into the PHI if the phi and fcmp are in the same
6306 // block. If in the same block, we're encouraging jump threading. If
6307 // not, we are just pessimizing the code by making an i1 phi.
6308 if (LHSI->getParent() == I.getParent())
6309 if (Instruction *NV = FoldOpIntoPhi(I))
6310 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006311 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006312 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006313 // If either operand of the select is a constant, we can fold the
6314 // comparison into the select arms, which will cause one to be
6315 // constant folded and the select turned into a bitwise or.
6316 Value *Op1 = 0, *Op2 = 0;
6317 if (LHSI->hasOneUse()) {
6318 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6319 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006320 Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006321 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006322 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006323 LHSI->getOperand(2), RHSC,
6324 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006325 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6326 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006327 Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006328 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006329 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006330 LHSI->getOperand(1), RHSC,
6331 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006332 }
6333 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006334
Chris Lattner6970b662005-04-23 15:31:55 +00006335 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006336 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006337 break;
6338 }
Chris Lattner4802d902007-04-06 18:57:34 +00006339 case Instruction::Malloc:
6340 // If we have (malloc != null), and if the malloc has a single use, we
6341 // can assume it is successful and remove the malloc.
6342 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6343 AddToWorkList(LHSI);
Owen Andersond672ecb2009-07-03 00:17:18 +00006344 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006345 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006346 }
6347 break;
6348 }
Chris Lattner6970b662005-04-23 15:31:55 +00006349 }
6350
Reid Spencere4d87aa2006-12-23 06:05:41 +00006351 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006352 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006353 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006354 return NI;
6355 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006356 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6357 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006358 return NI;
6359
Reid Spencere4d87aa2006-12-23 06:05:41 +00006360 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006361 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6362 // now.
6363 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6364 if (isa<PointerType>(Op0->getType()) &&
6365 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006366 // We keep moving the cast from the left operand over to the right
6367 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006368 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006369
Chris Lattner57d86372007-01-06 01:45:59 +00006370 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6371 // so eliminate it as well.
6372 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6373 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006374
Chris Lattnerde90b762003-11-03 04:25:02 +00006375 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006376 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006377 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006378 Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006379 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006380 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006381 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006382 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006383 }
Owen Anderson333c4002009-07-09 23:48:35 +00006384 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006385 }
Chris Lattner57d86372007-01-06 01:45:59 +00006386 }
6387
6388 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006389 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006390 // This comes up when you have code like
6391 // int X = A < B;
6392 // if (X) ...
6393 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006394 // with a constant or another cast from the same type.
6395 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006396 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006397 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006398 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006399
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006400 // See if it's the same type of instruction on the left and right.
6401 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6402 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006403 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006404 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006405 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006406 default: break;
6407 case Instruction::Add:
6408 case Instruction::Sub:
6409 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006410 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Owen Anderson333c4002009-07-09 23:48:35 +00006411 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006412 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006413 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6414 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6415 if (CI->getValue().isSignBit()) {
6416 ICmpInst::Predicate Pred = I.isSignedPredicate()
6417 ? I.getUnsignedPredicate()
6418 : I.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006419 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006420 Op1I->getOperand(0));
6421 }
6422
6423 if (CI->getValue().isMaxSignedValue()) {
6424 ICmpInst::Predicate Pred = I.isSignedPredicate()
6425 ? I.getUnsignedPredicate()
6426 : I.getSignedPredicate();
6427 Pred = I.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006428 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006429 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006430 }
6431 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006432 break;
6433 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006434 if (!I.isEquality())
6435 break;
6436
Nick Lewycky5d52c452008-08-21 05:56:10 +00006437 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6438 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6439 // Mask = -1 >> count-trailing-zeros(Cst).
6440 if (!CI->isZero() && !CI->isOne()) {
6441 const APInt &AP = CI->getValue();
Owen Andersond672ecb2009-07-03 00:17:18 +00006442 ConstantInt *Mask = Context->getConstantInt(
Nick Lewycky5d52c452008-08-21 05:56:10 +00006443 APInt::getLowBitsSet(AP.getBitWidth(),
6444 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006445 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006446 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6447 Mask);
6448 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6449 Mask);
6450 InsertNewInstBefore(And1, I);
6451 InsertNewInstBefore(And2, I);
Owen Anderson333c4002009-07-09 23:48:35 +00006452 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006453 }
6454 }
6455 break;
6456 }
6457 }
6458 }
6459 }
6460
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006461 // ~x < ~y --> y < x
6462 { Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006463 if (match(Op0, m_Not(m_Value(A)), *Context) &&
6464 match(Op1, m_Not(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006465 return new ICmpInst(*Context, I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006466 }
6467
Chris Lattner65b72ba2006-09-18 04:22:48 +00006468 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006469 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006470
6471 // -x == -y --> x == y
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006472 if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6473 match(Op1, m_Neg(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006474 return new ICmpInst(*Context, I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006475
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006476 if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006477 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6478 Value *OtherVal = A == Op1 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006479 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006480 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006481 }
6482
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006483 if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006484 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006485 ConstantInt *C1, *C2;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006486 if (match(B, m_ConstantInt(C1), *Context) &&
6487 match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006488 Constant *NC =
6489 Context->getConstantInt(C1->getValue() ^ C2->getValue());
Chris Lattnercb504b92008-11-16 05:38:51 +00006490 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Owen Anderson333c4002009-07-09 23:48:35 +00006491 return new ICmpInst(*Context, I.getPredicate(), A,
Chris Lattnercb504b92008-11-16 05:38:51 +00006492 InsertNewInstBefore(Xor, I));
6493 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006494
6495 // A^B == A^D -> B == D
Owen Anderson333c4002009-07-09 23:48:35 +00006496 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6497 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6498 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6499 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006500 }
6501 }
6502
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006503 if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006504 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006505 // A == (A^B) -> B == 0
6506 Value *OtherVal = A == Op0 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006507 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006508 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006509 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006510
6511 // (A-B) == A -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006512 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006513 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006514 Context->getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006515
6516 // A == (A-B) -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006517 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006518 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006519 Context->getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006520
Chris Lattner9c2328e2006-11-14 06:06:06 +00006521 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6522 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006523 match(Op0, m_And(m_Value(A), m_Value(B)), *Context) &&
6524 match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006525 Value *X = 0, *Y = 0, *Z = 0;
6526
6527 if (A == C) {
6528 X = B; Y = D; Z = A;
6529 } else if (A == D) {
6530 X = B; Y = C; Z = A;
6531 } else if (B == C) {
6532 X = A; Y = D; Z = B;
6533 } else if (B == D) {
6534 X = A; Y = C; Z = B;
6535 }
6536
6537 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006538 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6539 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006540 I.setOperand(0, Op1);
Owen Andersond672ecb2009-07-03 00:17:18 +00006541 I.setOperand(1, Context->getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006542 return &I;
6543 }
6544 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006545 }
Chris Lattner7e708292002-06-25 16:13:24 +00006546 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006547}
6548
Chris Lattner562ef782007-06-20 23:46:26 +00006549
6550/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6551/// and CmpRHS are both known to be integer constants.
6552Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6553 ConstantInt *DivRHS) {
6554 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6555 const APInt &CmpRHSV = CmpRHS->getValue();
6556
6557 // FIXME: If the operand types don't match the type of the divide
6558 // then don't attempt this transform. The code below doesn't have the
6559 // logic to deal with a signed divide and an unsigned compare (and
6560 // vice versa). This is because (x /s C1) <s C2 produces different
6561 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6562 // (x /u C1) <u C2. Simply casting the operands and result won't
6563 // work. :( The if statement below tests that condition and bails
6564 // if it finds it.
6565 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6566 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6567 return 0;
6568 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006569 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006570 if (DivIsSigned && DivRHS->isAllOnesValue())
6571 return 0; // The overflow computation also screws up here
6572 if (DivRHS->isOne())
6573 return 0; // Not worth bothering, and eliminates some funny cases
6574 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006575
6576 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6577 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6578 // C2 (CI). By solving for X we can turn this into a range check
6579 // instead of computing a divide.
Owen Andersond672ecb2009-07-03 00:17:18 +00006580 Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006581
6582 // Determine if the product overflows by seeing if the product is
6583 // not equal to the divide. Make sure we do the same kind of divide
6584 // as in the LHS instruction that we're folding.
Owen Andersond672ecb2009-07-03 00:17:18 +00006585 bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6586 Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006587
6588 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006589 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006590
Chris Lattner1dbfd482007-06-21 18:11:19 +00006591 // Figure out the interval that is being checked. For example, a comparison
6592 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6593 // Compute this interval based on the constants involved and the signedness of
6594 // the compare/divide. This computes a half-open interval, keeping track of
6595 // whether either value in the interval overflows. After analysis each
6596 // overflow variable is set to 0 if it's corresponding bound variable is valid
6597 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6598 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006599 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006600
Chris Lattner562ef782007-06-20 23:46:26 +00006601 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006602 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006603 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006604 HiOverflow = LoOverflow = ProdOV;
6605 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006606 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006607 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006608 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006609 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00006610 LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS,
6611 Context)));
Chris Lattner562ef782007-06-20 23:46:26 +00006612 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006613 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006614 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6615 HiOverflow = LoOverflow = ProdOV;
6616 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006617 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006618 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006619 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006620 HiBound = AddOne(Prod, Context);
Chris Lattnera6321b42008-10-11 22:55:00 +00006621 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6622 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006623 ConstantInt* DivNeg =
6624 cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6625 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006626 true) ? -1 : 0;
6627 }
Chris Lattner562ef782007-06-20 23:46:26 +00006628 }
Dan Gohman76491272008-02-13 22:09:18 +00006629 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006630 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006631 // e.g. X/-5 op 0 --> [-4, 5)
Owen Andersond672ecb2009-07-03 00:17:18 +00006632 LoBound = AddOne(DivRHS, Context);
6633 HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006634 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6635 HiOverflow = 1; // [INTMIN+1, overflow)
6636 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6637 }
Dan Gohman76491272008-02-13 22:09:18 +00006638 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006639 // e.g. X/-5 op 3 --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006640 HiBound = AddOne(Prod, Context);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006641 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006642 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006643 LoOverflow = AddWithOverflow(LoBound, HiBound,
6644 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006645 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006646 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6647 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006648 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006649 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006650 }
6651
Chris Lattner1dbfd482007-06-21 18:11:19 +00006652 // Dividing by a negative swaps the condition. LT <-> GT
6653 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006654 }
6655
6656 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006657 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006658 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006659 case ICmpInst::ICMP_EQ:
6660 if (LoOverflow && HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006661 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattner562ef782007-06-20 23:46:26 +00006662 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006663 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006664 ICmpInst::ICMP_UGE, X, LoBound);
6665 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006666 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006667 ICmpInst::ICMP_ULT, X, HiBound);
6668 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006669 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006670 case ICmpInst::ICMP_NE:
6671 if (LoOverflow && HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006672 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner562ef782007-06-20 23:46:26 +00006673 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006674 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006675 ICmpInst::ICMP_ULT, X, LoBound);
6676 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006677 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006678 ICmpInst::ICMP_UGE, X, HiBound);
6679 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006680 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006681 case ICmpInst::ICMP_ULT:
6682 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006683 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006684 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006685 if (LoOverflow == -1) // Low bound is less than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006686 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00006687 return new ICmpInst(*Context, Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006688 case ICmpInst::ICMP_UGT:
6689 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006690 if (HiOverflow == +1) // High bound greater than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006691 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006692 else if (HiOverflow == -1) // High bound less than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006693 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006694 if (Pred == ICmpInst::ICMP_UGT)
Owen Anderson333c4002009-07-09 23:48:35 +00006695 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006696 else
Owen Anderson333c4002009-07-09 23:48:35 +00006697 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006698 }
6699}
6700
6701
Chris Lattner01deb9d2007-04-03 17:43:25 +00006702/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6703///
6704Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6705 Instruction *LHSI,
6706 ConstantInt *RHS) {
6707 const APInt &RHSV = RHS->getValue();
6708
6709 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006710 case Instruction::Trunc:
6711 if (ICI.isEquality() && LHSI->hasOneUse()) {
6712 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6713 // of the high bits truncated out of x are known.
6714 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6715 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6716 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6717 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6718 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6719
6720 // If all the high bits are known, we can do this xform.
6721 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6722 // Pull in the high bits from known-ones set.
6723 APInt NewRHS(RHS->getValue());
6724 NewRHS.zext(SrcBits);
6725 NewRHS |= KnownOne;
Owen Anderson333c4002009-07-09 23:48:35 +00006726 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006727 Context->getConstantInt(NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006728 }
6729 }
6730 break;
6731
Duncan Sands0091bf22007-04-04 06:42:45 +00006732 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006733 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6734 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6735 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006736 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6737 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006738 Value *CompareVal = LHSI->getOperand(0);
6739
6740 // If the sign bit of the XorCST is not set, there is no change to
6741 // the operation, just stop using the Xor.
6742 if (!XorCST->getValue().isNegative()) {
6743 ICI.setOperand(0, CompareVal);
6744 AddToWorkList(LHSI);
6745 return &ICI;
6746 }
6747
6748 // Was the old condition true if the operand is positive?
6749 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6750
6751 // If so, the new one isn't.
6752 isTrueIfPositive ^= true;
6753
6754 if (isTrueIfPositive)
Owen Anderson333c4002009-07-09 23:48:35 +00006755 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006756 SubOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006757 else
Owen Anderson333c4002009-07-09 23:48:35 +00006758 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006759 AddOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006760 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006761
6762 if (LHSI->hasOneUse()) {
6763 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6764 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6765 const APInt &SignBit = XorCST->getValue();
6766 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6767 ? ICI.getUnsignedPredicate()
6768 : ICI.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006769 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006770 Context->getConstantInt(RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006771 }
6772
6773 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006774 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006775 const APInt &NotSignBit = XorCST->getValue();
6776 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6777 ? ICI.getUnsignedPredicate()
6778 : ICI.getSignedPredicate();
6779 Pred = ICI.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006780 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006781 Context->getConstantInt(RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006782 }
6783 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006784 }
6785 break;
6786 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6787 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6788 LHSI->getOperand(0)->hasOneUse()) {
6789 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6790
6791 // If the LHS is an AND of a truncating cast, we can widen the
6792 // and/compare to be the input width without changing the value
6793 // produced, eliminating a cast.
6794 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6795 // We can do this transformation if either the AND constant does not
6796 // have its sign bit set or if it is an equality comparison.
6797 // Extending a relational comparison when we're checking the sign
6798 // bit would not work.
6799 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006800 (ICI.isEquality() ||
6801 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006802 uint32_t BitWidth =
6803 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6804 APInt NewCST = AndCST->getValue();
6805 NewCST.zext(BitWidth);
6806 APInt NewCI = RHSV;
6807 NewCI.zext(BitWidth);
6808 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006809 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006810 Context->getConstantInt(NewCST),LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006811 InsertNewInstBefore(NewAnd, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006812 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
Owen Andersond672ecb2009-07-03 00:17:18 +00006813 Context->getConstantInt(NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006814 }
6815 }
6816
6817 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6818 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6819 // happens a LOT in code produced by the C front-end, for bitfield
6820 // access.
6821 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6822 if (Shift && !Shift->isShift())
6823 Shift = 0;
6824
6825 ConstantInt *ShAmt;
6826 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6827 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6828 const Type *AndTy = AndCST->getType(); // Type of the and.
6829
6830 // We can fold this as long as we can't shift unknown bits
6831 // into the mask. This can only happen with signed shift
6832 // rights, as they sign-extend.
6833 if (ShAmt) {
6834 bool CanFold = Shift->isLogicalShift();
6835 if (!CanFold) {
6836 // To test for the bad case of the signed shr, see if any
6837 // of the bits shifted in could be tested after the mask.
6838 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6839 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6840
6841 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6842 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6843 AndCST->getValue()) == 0)
6844 CanFold = true;
6845 }
6846
6847 if (CanFold) {
6848 Constant *NewCst;
6849 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006850 NewCst = Context->getConstantExprLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006851 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006852 NewCst = Context->getConstantExprShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006853
6854 // Check to see if we are shifting out any of the bits being
6855 // compared.
Owen Andersond672ecb2009-07-03 00:17:18 +00006856 if (Context->getConstantExpr(Shift->getOpcode(),
6857 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006858 // If we shifted bits out, the fold is not going to work out.
6859 // As a special case, check to see if this means that the
6860 // result is always true or false now.
6861 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersond672ecb2009-07-03 00:17:18 +00006862 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006863 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersond672ecb2009-07-03 00:17:18 +00006864 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006865 } else {
6866 ICI.setOperand(1, NewCst);
6867 Constant *NewAndCST;
6868 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006869 NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006870 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006871 NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006872 LHSI->setOperand(1, NewAndCST);
6873 LHSI->setOperand(0, Shift->getOperand(0));
6874 AddToWorkList(Shift); // Shift is dead.
6875 AddUsesToWorkList(ICI);
6876 return &ICI;
6877 }
6878 }
6879 }
6880
6881 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6882 // preferable because it allows the C<<Y expression to be hoisted out
6883 // of a loop if Y is invariant and X is not.
6884 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006885 ICI.isEquality() && !Shift->isArithmeticShift() &&
6886 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006887 // Compute C << Y.
6888 Value *NS;
6889 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006890 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006891 Shift->getOperand(1), "tmp");
6892 } else {
6893 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006894 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006895 Shift->getOperand(1), "tmp");
6896 }
6897 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6898
6899 // Compute X & (C << Y).
6900 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006901 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006902 InsertNewInstBefore(NewAnd, ICI);
6903
6904 ICI.setOperand(0, NewAnd);
6905 return &ICI;
6906 }
6907 }
6908 break;
6909
Chris Lattnera0141b92007-07-15 20:42:37 +00006910 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6911 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6912 if (!ShAmt) break;
6913
6914 uint32_t TypeBits = RHSV.getBitWidth();
6915
6916 // Check that the shift amount is in range. If not, don't perform
6917 // undefined shifts. When the shift is visited it will be
6918 // simplified.
6919 if (ShAmt->uge(TypeBits))
6920 break;
6921
6922 if (ICI.isEquality()) {
6923 // If we are comparing against bits always shifted out, the
6924 // comparison cannot succeed.
6925 Constant *Comp =
Owen Andersond672ecb2009-07-03 00:17:18 +00006926 Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6927 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006928 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6929 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersond672ecb2009-07-03 00:17:18 +00006930 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006931 return ReplaceInstUsesWith(ICI, Cst);
6932 }
6933
6934 if (LHSI->hasOneUse()) {
6935 // Otherwise strength reduce the shift into an and.
6936 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6937 Constant *Mask =
Owen Andersond672ecb2009-07-03 00:17:18 +00006938 Context->getConstantInt(APInt::getLowBitsSet(TypeBits,
6939 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006940
Chris Lattnera0141b92007-07-15 20:42:37 +00006941 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006942 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006943 Mask, LHSI->getName()+".mask");
6944 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006945 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00006946 Context->getConstantInt(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006947 }
6948 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006949
6950 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6951 bool TrueIfSigned = false;
6952 if (LHSI->hasOneUse() &&
6953 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6954 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersond672ecb2009-07-03 00:17:18 +00006955 Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006956 (TypeBits-ShAmt->getZExtValue()-1));
6957 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006958 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006959 Mask, LHSI->getName()+".mask");
6960 Value *And = InsertNewInstBefore(AndI, ICI);
6961
Owen Anderson333c4002009-07-09 23:48:35 +00006962 return new ICmpInst(*Context,
6963 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersond672ecb2009-07-03 00:17:18 +00006964 And, Context->getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006965 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006966 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006967 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006968
6969 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006970 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006971 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006972 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006973 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006974
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006975 // Check that the shift amount is in range. If not, don't perform
6976 // undefined shifts. When the shift is visited it will be
6977 // simplified.
6978 uint32_t TypeBits = RHSV.getBitWidth();
6979 if (ShAmt->uge(TypeBits))
6980 break;
6981
6982 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006983
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006984 // If we are comparing against bits always shifted out, the
6985 // comparison cannot succeed.
6986 APInt Comp = RHSV << ShAmtVal;
6987 if (LHSI->getOpcode() == Instruction::LShr)
6988 Comp = Comp.lshr(ShAmtVal);
6989 else
6990 Comp = Comp.ashr(ShAmtVal);
6991
6992 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6993 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersond672ecb2009-07-03 00:17:18 +00006994 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006995 return ReplaceInstUsesWith(ICI, Cst);
6996 }
6997
6998 // Otherwise, check to see if the bits shifted out are known to be zero.
6999 // If so, we can compare against the unshifted value:
7000 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007001 if (LHSI->hasOneUse() &&
7002 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007003 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Owen Anderson333c4002009-07-09 23:48:35 +00007004 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007005 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007006 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007007
Evan Chengf30752c2008-04-23 00:38:06 +00007008 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007009 // Otherwise strength reduce the shift into an and.
7010 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00007011 Constant *Mask = Context->getConstantInt(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007012
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007013 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007014 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007015 Mask, LHSI->getName()+".mask");
7016 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007017 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00007018 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007019 }
7020 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007021 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007022
7023 case Instruction::SDiv:
7024 case Instruction::UDiv:
7025 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7026 // Fold this div into the comparison, producing a range check.
7027 // Determine, based on the divide type, what the range is being
7028 // checked. If there is an overflow on the low or high side, remember
7029 // it, otherwise compute the range [low, hi) bounding the new value.
7030 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007031 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7032 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7033 DivRHS))
7034 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007035 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007036
7037 case Instruction::Add:
7038 // Fold: icmp pred (add, X, C1), C2
7039
7040 if (!ICI.isEquality()) {
7041 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7042 if (!LHSC) break;
7043 const APInt &LHSV = LHSC->getValue();
7044
7045 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7046 .subtract(LHSV);
7047
7048 if (ICI.isSignedPredicate()) {
7049 if (CR.getLower().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007050 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007051 Context->getConstantInt(CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007052 } else if (CR.getUpper().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007053 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007054 Context->getConstantInt(CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007055 }
7056 } else {
7057 if (CR.getLower().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007058 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007059 Context->getConstantInt(CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007060 } else if (CR.getUpper().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007061 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007062 Context->getConstantInt(CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007063 }
7064 }
7065 }
7066 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007067 }
7068
7069 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7070 if (ICI.isEquality()) {
7071 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7072
7073 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7074 // the second operand is a constant, simplify a bit.
7075 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7076 switch (BO->getOpcode()) {
7077 case Instruction::SRem:
7078 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7079 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7080 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7081 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7082 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007083 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007084 BO->getName());
7085 InsertNewInstBefore(NewRem, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007086 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
Owen Andersond672ecb2009-07-03 00:17:18 +00007087 Context->getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007088 }
7089 }
7090 break;
7091 case Instruction::Add:
7092 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7093 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7094 if (BO->hasOneUse())
Owen Anderson333c4002009-07-09 23:48:35 +00007095 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007096 Context->getConstantExprSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007097 } else if (RHSV == 0) {
7098 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7099 // efficiently invertible, or if the add has just this one use.
7100 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7101
Owen Andersond672ecb2009-07-03 00:17:18 +00007102 if (Value *NegVal = dyn_castNegVal(BOp1, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007103 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
Owen Andersond672ecb2009-07-03 00:17:18 +00007104 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007105 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007106 else if (BO->hasOneUse()) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00007107 Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007108 InsertNewInstBefore(Neg, ICI);
7109 Neg->takeName(BO);
Owen Anderson333c4002009-07-09 23:48:35 +00007110 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007111 }
7112 }
7113 break;
7114 case Instruction::Xor:
7115 // For the xor case, we can xor two constants together, eliminating
7116 // the explicit xor.
7117 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Owen Anderson333c4002009-07-09 23:48:35 +00007118 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007119 Context->getConstantExprXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007120
7121 // FALLTHROUGH
7122 case Instruction::Sub:
7123 // Replace (([sub|xor] A, B) != 0) with (A != B)
7124 if (RHSV == 0)
Owen Anderson333c4002009-07-09 23:48:35 +00007125 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007126 BO->getOperand(1));
7127 break;
7128
7129 case Instruction::Or:
7130 // If bits are being or'd in that are not present in the constant we
7131 // are comparing against, then the comparison could never succeed!
7132 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007133 Constant *NotCI = Context->getConstantExprNot(RHS);
7134 if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7135 return ReplaceInstUsesWith(ICI,
7136 Context->getConstantInt(Type::Int1Ty,
7137 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007138 }
7139 break;
7140
7141 case Instruction::And:
7142 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7143 // If bits are being compared against that are and'd out, then the
7144 // comparison can never succeed!
7145 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007146 return ReplaceInstUsesWith(ICI,
7147 Context->getConstantInt(Type::Int1Ty,
7148 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007149
7150 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7151 if (RHS == BOC && RHSV.isPowerOf2())
Owen Anderson333c4002009-07-09 23:48:35 +00007152 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007153 ICmpInst::ICMP_NE, LHSI,
Owen Andersond672ecb2009-07-03 00:17:18 +00007154 Context->getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007155
7156 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007157 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007158 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007159 Constant *Zero = Context->getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007160 ICmpInst::Predicate pred = isICMP_NE ?
7161 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Owen Anderson333c4002009-07-09 23:48:35 +00007162 return new ICmpInst(*Context, pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007163 }
7164
7165 // ((X & ~7) == 0) --> X < 8
7166 if (RHSV == 0 && isHighOnes(BOC)) {
7167 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007168 Constant *NegX = Context->getConstantExprNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007169 ICmpInst::Predicate pred = isICMP_NE ?
7170 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Owen Anderson333c4002009-07-09 23:48:35 +00007171 return new ICmpInst(*Context, pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007172 }
7173 }
7174 default: break;
7175 }
7176 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7177 // Handle icmp {eq|ne} <intrinsic>, intcst.
7178 if (II->getIntrinsicID() == Intrinsic::bswap) {
7179 AddToWorkList(II);
7180 ICI.setOperand(0, II->getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007181 ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007182 return &ICI;
7183 }
7184 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007185 }
7186 return 0;
7187}
7188
7189/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7190/// We only handle extending casts so far.
7191///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007192Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7193 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007194 Value *LHSCIOp = LHSCI->getOperand(0);
7195 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007196 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007197 Value *RHSCIOp;
7198
Chris Lattner8c756c12007-05-05 22:41:33 +00007199 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7200 // integer type is the same size as the pointer type.
7201 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7202 getTargetData().getPointerSizeInBits() ==
7203 cast<IntegerType>(DestTy)->getBitWidth()) {
7204 Value *RHSOp = 0;
7205 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007206 RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007207 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7208 RHSOp = RHSC->getOperand(0);
7209 // If the pointer types don't match, insert a bitcast.
7210 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007211 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007212 }
7213
7214 if (RHSOp)
Owen Anderson333c4002009-07-09 23:48:35 +00007215 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007216 }
7217
7218 // The code below only handles extension cast instructions, so far.
7219 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007220 if (LHSCI->getOpcode() != Instruction::ZExt &&
7221 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007222 return 0;
7223
Reid Spencere4d87aa2006-12-23 06:05:41 +00007224 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7225 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007226
Reid Spencere4d87aa2006-12-23 06:05:41 +00007227 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007228 // Not an extension from the same type?
7229 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007230 if (RHSCIOp->getType() != LHSCIOp->getType())
7231 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007232
Nick Lewycky4189a532008-01-28 03:48:02 +00007233 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007234 // and the other is a zext), then we can't handle this.
7235 if (CI->getOpcode() != LHSCI->getOpcode())
7236 return 0;
7237
Nick Lewycky4189a532008-01-28 03:48:02 +00007238 // Deal with equality cases early.
7239 if (ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007240 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007241
7242 // A signed comparison of sign extended values simplifies into a
7243 // signed comparison.
7244 if (isSignedCmp && isSignedExt)
Owen Anderson333c4002009-07-09 23:48:35 +00007245 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007246
7247 // The other three cases all fold into an unsigned comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00007248 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007249 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007250
Reid Spencere4d87aa2006-12-23 06:05:41 +00007251 // If we aren't dealing with a constant on the RHS, exit early
7252 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7253 if (!CI)
7254 return 0;
7255
7256 // Compute the constant that would happen if we truncated to SrcTy then
7257 // reextended to DestTy.
Owen Andersond672ecb2009-07-03 00:17:18 +00007258 Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7259 Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7260 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007261
7262 // If the re-extended constant didn't change...
7263 if (Res2 == CI) {
7264 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7265 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007266 // %A = sext i16 %X to i32
7267 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007268 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007269 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007270 // because %A may have negative value.
7271 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007272 // However, we allow this when the compare is EQ/NE, because they are
7273 // signless.
7274 if (isSignedExt == isSignedCmp || ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007275 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007276 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007277 }
7278
7279 // The re-extended constant changed so the constant cannot be represented
7280 // in the shorter type. Consequently, we cannot emit a simple comparison.
7281
7282 // First, handle some easy cases. We know the result cannot be equal at this
7283 // point so handle the ICI.isEquality() cases
7284 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersond672ecb2009-07-03 00:17:18 +00007285 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007286 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersond672ecb2009-07-03 00:17:18 +00007287 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007288
7289 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7290 // should have been folded away previously and not enter in here.
7291 Value *Result;
7292 if (isSignedCmp) {
7293 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007294 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00007295 Result = Context->getConstantIntFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007296 else
Owen Andersond672ecb2009-07-03 00:17:18 +00007297 Result = Context->getConstantIntTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007298 } else {
7299 // We're performing an unsigned comparison.
7300 if (isSignedExt) {
7301 // We're performing an unsigned comp with a sign extended value.
7302 // This is true if the input is >= 0. [aka >s -1]
Owen Anderson73c6b712009-07-13 20:58:05 +00007303 Constant *NegOne = Context->getAllOnesValue(SrcTy);
Owen Anderson333c4002009-07-09 23:48:35 +00007304 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7305 LHSCIOp, NegOne, ICI.getName()), ICI);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007306 } else {
7307 // Unsigned extend & unsigned compare -> always true.
Owen Andersond672ecb2009-07-03 00:17:18 +00007308 Result = Context->getConstantIntTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007309 }
7310 }
7311
7312 // Finally, return the value computed.
7313 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007314 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007315 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007316
7317 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7318 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7319 "ICmp should be folded!");
7320 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00007321 return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
Owen Anderson73c6b712009-07-13 20:58:05 +00007322 return BinaryOperator::CreateNot(*Context, Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007323}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007324
Reid Spencer832254e2007-02-02 02:16:23 +00007325Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7326 return commonShiftTransforms(I);
7327}
7328
7329Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7330 return commonShiftTransforms(I);
7331}
7332
7333Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007334 if (Instruction *R = commonShiftTransforms(I))
7335 return R;
7336
7337 Value *Op0 = I.getOperand(0);
7338
7339 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7340 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7341 if (CSI->isAllOnesValue())
7342 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007343
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007344 // See if we can turn a signed shr into an unsigned shr.
7345 if (MaskedValueIsZero(Op0,
7346 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7347 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7348
7349 // Arithmetic shifting an all-sign-bit value is a no-op.
7350 unsigned NumSignBits = ComputeNumSignBits(Op0);
7351 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7352 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007353
Chris Lattner348f6652007-12-06 01:59:46 +00007354 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007355}
7356
7357Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7358 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007359 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007360
7361 // shl X, 0 == X and shr X, 0 == X
7362 // shl 0, X == 0 and shr 0, X == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007363 if (Op1 == Context->getNullValue(Op1->getType()) ||
7364 Op0 == Context->getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007365 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007366
Reid Spencere4d87aa2006-12-23 06:05:41 +00007367 if (isa<UndefValue>(Op0)) {
7368 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007369 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007370 else // undef << X -> 0, undef >>u X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007371 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007372 }
7373 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007374 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7375 return ReplaceInstUsesWith(I, Op0);
7376 else // X << undef, X >>u undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007377 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007378 }
7379
Dan Gohman9004c8a2009-05-21 02:28:33 +00007380 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007381 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007382 return &I;
7383
Chris Lattner2eefe512004-04-09 19:05:30 +00007384 // Try to fold constant and into select arguments.
7385 if (isa<Constant>(Op0))
7386 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007387 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007388 return R;
7389
Reid Spencerb83eb642006-10-20 07:07:24 +00007390 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007391 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7392 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007393 return 0;
7394}
7395
Reid Spencerb83eb642006-10-20 07:07:24 +00007396Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007397 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007398 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007399
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007400 // See if we can simplify any instructions used by the instruction whose sole
7401 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007402 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007403
Dan Gohmana119de82009-06-14 23:30:43 +00007404 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7405 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007406 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007407 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007408 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007409 return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007410 else {
Owen Andersond672ecb2009-07-03 00:17:18 +00007411 I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007412 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007413 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007414 }
7415
7416 // ((X*C1) << C2) == (X * (C1 << C2))
7417 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7418 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7419 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007420 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007421 Context->getConstantExprShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007422
7423 // Try to fold constant and into select arguments.
7424 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7425 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7426 return R;
7427 if (isa<PHINode>(Op0))
7428 if (Instruction *NV = FoldOpIntoPhi(I))
7429 return NV;
7430
Chris Lattner8999dd32007-12-22 09:07:47 +00007431 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7432 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7433 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7434 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7435 // place. Don't try to do this transformation in this case. Also, we
7436 // require that the input operand is a shift-by-constant so that we have
7437 // confidence that the shifts will get folded together. We could do this
7438 // xform in more cases, but it is unlikely to be profitable.
7439 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7440 isa<ConstantInt>(TrOp->getOperand(1))) {
7441 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersond672ecb2009-07-03 00:17:18 +00007442 Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007443 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007444 I.getName());
7445 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7446
7447 // For logical shifts, the truncation has the effect of making the high
7448 // part of the register be zeros. Emulate this by inserting an AND to
7449 // clear the top bits as needed. This 'and' will usually be zapped by
7450 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007451 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7452 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007453 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7454
7455 // The mask we constructed says what the trunc would do if occurring
7456 // between the shifts. We want to know the effect *after* the second
7457 // shift. We know that it is a logical shift by a constant, so adjust the
7458 // mask as appropriate.
7459 if (I.getOpcode() == Instruction::Shl)
7460 MaskV <<= Op1->getZExtValue();
7461 else {
7462 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7463 MaskV = MaskV.lshr(Op1->getZExtValue());
7464 }
7465
Owen Andersond672ecb2009-07-03 00:17:18 +00007466 Instruction *And =
7467 BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV),
7468 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007469 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7470
7471 // Return the value truncated to the interesting size.
7472 return new TruncInst(And, I.getType());
7473 }
7474 }
7475
Chris Lattner4d5542c2006-01-06 07:12:35 +00007476 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007477 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7478 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7479 Value *V1, *V2;
7480 ConstantInt *CC;
7481 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007482 default: break;
7483 case Instruction::Add:
7484 case Instruction::And:
7485 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007486 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007487 // These operators commute.
7488 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007489 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007490 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7491 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007492 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007493 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007494 Op0BO->getName());
7495 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007496 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007497 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007498 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007499 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007500 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersond672ecb2009-07-03 00:17:18 +00007501 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng90b96812007-03-30 05:45:18 +00007502 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007503 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007504
Chris Lattner150f12a2005-09-18 06:30:59 +00007505 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007506 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007507 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007508 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007509 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007510 m_ConstantInt(CC)), *Context) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007511 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007512 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007513 Op0BO->getOperand(0), Op1,
7514 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007515 InsertNewInstBefore(YS, I); // (Y << C)
7516 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007517 BinaryOperator::CreateAnd(V1,
7518 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007519 V1->getName()+".mask");
7520 InsertNewInstBefore(XM, I); // X & (CC << C)
7521
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007522 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007523 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007524 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007525
Reid Spencera07cb7d2007-02-02 14:41:37 +00007526 // FALL THROUGH.
7527 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007528 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007529 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007530 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7531 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007532 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007533 Op0BO->getOperand(1), Op1,
7534 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007535 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007536 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007537 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007538 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007539 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007540 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersond672ecb2009-07-03 00:17:18 +00007541 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng90b96812007-03-30 05:45:18 +00007542 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007543 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007544
Chris Lattner13d4ab42006-05-31 21:14:00 +00007545 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007546 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7547 match(Op0BO->getOperand(0),
7548 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007549 m_ConstantInt(CC)), *Context) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007550 cast<BinaryOperator>(Op0BO->getOperand(0))
7551 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007552 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007553 Op0BO->getOperand(1), Op1,
7554 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007555 InsertNewInstBefore(YS, I); // (Y << C)
7556 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007557 BinaryOperator::CreateAnd(V1,
7558 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007559 V1->getName()+".mask");
7560 InsertNewInstBefore(XM, I); // X & (CC << C)
7561
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007562 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007563 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007564
Chris Lattner11021cb2005-09-18 05:12:10 +00007565 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007566 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007567 }
7568
7569
7570 // If the operand is an bitwise operator with a constant RHS, and the
7571 // shift is the only use, we can pull it out of the shift.
7572 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7573 bool isValid = true; // Valid only for And, Or, Xor
7574 bool highBitSet = false; // Transform if high bit of constant set?
7575
7576 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007577 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007578 case Instruction::Add:
7579 isValid = isLeftShift;
7580 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007581 case Instruction::Or:
7582 case Instruction::Xor:
7583 highBitSet = false;
7584 break;
7585 case Instruction::And:
7586 highBitSet = true;
7587 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007588 }
7589
7590 // If this is a signed shift right, and the high bit is modified
7591 // by the logical operation, do not perform the transformation.
7592 // The highBitSet boolean indicates the value of the high bit of
7593 // the constant which would cause it to be modified for this
7594 // operation.
7595 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007596 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007597 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007598
7599 if (isValid) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007600 Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007601
7602 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007603 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007604 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007605 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007606
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007607 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007608 NewRHS);
7609 }
7610 }
7611 }
7612 }
7613
Chris Lattnerad0124c2006-01-06 07:52:12 +00007614 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007615 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7616 if (ShiftOp && !ShiftOp->isShift())
7617 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007618
Reid Spencerb83eb642006-10-20 07:07:24 +00007619 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007620 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007621 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7622 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007623 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7624 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7625 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007626
Zhou Sheng4351c642007-04-02 08:20:41 +00007627 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007628
7629 const IntegerType *Ty = cast<IntegerType>(I.getType());
7630
7631 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007632 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007633 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7634 // saturates.
7635 if (AmtSum >= TypeBits) {
7636 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007637 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007638 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7639 }
7640
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007641 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersond672ecb2009-07-03 00:17:18 +00007642 Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007643 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7644 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007645 if (AmtSum >= TypeBits)
Owen Andersond672ecb2009-07-03 00:17:18 +00007646 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007647
Chris Lattnerb87056f2007-02-05 00:57:54 +00007648 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersond672ecb2009-07-03 00:17:18 +00007649 return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007650 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7651 I.getOpcode() == Instruction::LShr) {
7652 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007653 if (AmtSum >= TypeBits)
7654 AmtSum = TypeBits-1;
7655
Chris Lattnerb87056f2007-02-05 00:57:54 +00007656 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007657 BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007658 InsertNewInstBefore(Shift, I);
7659
Zhou Shenge9e03f62007-03-28 15:02:20 +00007660 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007661 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007662 }
7663
Chris Lattnerb87056f2007-02-05 00:57:54 +00007664 // Okay, if we get here, one shift must be left, and the other shift must be
7665 // right. See if the amounts are equal.
7666 if (ShiftAmt1 == ShiftAmt2) {
7667 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7668 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007669 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007670 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007671 }
7672 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7673 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007674 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007675 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007676 }
7677 // We can simplify ((X << C) >>s C) into a trunc + sext.
7678 // NOTE: we could do this for any C, but that would make 'unusual' integer
7679 // types. For now, just stick to ones well-supported by the code
7680 // generators.
7681 const Type *SExtType = 0;
7682 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007683 case 1 :
7684 case 8 :
7685 case 16 :
7686 case 32 :
7687 case 64 :
7688 case 128:
Owen Andersond672ecb2009-07-03 00:17:18 +00007689 SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007690 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007691 default: break;
7692 }
7693 if (SExtType) {
7694 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7695 InsertNewInstBefore(NewTrunc, I);
7696 return new SExtInst(NewTrunc, Ty);
7697 }
7698 // Otherwise, we can't handle it yet.
7699 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007700 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007701
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007702 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007703 if (I.getOpcode() == Instruction::Shl) {
7704 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7705 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007706 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007707 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007708 InsertNewInstBefore(Shift, I);
7709
Reid Spencer55702aa2007-03-25 21:11:44 +00007710 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007711 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007712 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007713
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007714 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007715 if (I.getOpcode() == Instruction::LShr) {
7716 assert(ShiftOp->getOpcode() == Instruction::Shl);
7717 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007718 BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007719 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007720
Reid Spencerd5e30f02007-03-26 17:18:58 +00007721 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007722 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007723 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007724
7725 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7726 } else {
7727 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007728 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007729
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007730 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007731 if (I.getOpcode() == Instruction::Shl) {
7732 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7733 ShiftOp->getOpcode() == Instruction::AShr);
7734 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007735 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersond672ecb2009-07-03 00:17:18 +00007736 Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007737 InsertNewInstBefore(Shift, I);
7738
Reid Spencer55702aa2007-03-25 21:11:44 +00007739 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007740 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007741 }
7742
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007743 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007744 if (I.getOpcode() == Instruction::LShr) {
7745 assert(ShiftOp->getOpcode() == Instruction::Shl);
7746 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007747 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007748 InsertNewInstBefore(Shift, I);
7749
Reid Spencer68d27cf2007-03-26 23:45:51 +00007750 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007751 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007752 }
7753
7754 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007755 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007756 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007757 return 0;
7758}
7759
Chris Lattnera1be5662002-05-02 17:06:02 +00007760
Chris Lattnercfd65102005-10-29 04:36:15 +00007761/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7762/// expression. If so, decompose it, returning some value X, such that Val is
7763/// X*Scale+Offset.
7764///
7765static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007766 int &Offset, LLVMContext *Context) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007767 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007768 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007769 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007770 Scale = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00007771 return Context->getConstantInt(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007772 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7773 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7774 if (I->getOpcode() == Instruction::Shl) {
7775 // This is a value scaled by '1 << the shift amt'.
7776 Scale = 1U << RHS->getZExtValue();
7777 Offset = 0;
7778 return I->getOperand(0);
7779 } else if (I->getOpcode() == Instruction::Mul) {
7780 // This value is scaled by 'RHS'.
7781 Scale = RHS->getZExtValue();
7782 Offset = 0;
7783 return I->getOperand(0);
7784 } else if (I->getOpcode() == Instruction::Add) {
7785 // We have X+C. Check to see if we really have (X*C2)+C1,
7786 // where C1 is divisible by C2.
7787 unsigned SubScale;
7788 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007789 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7790 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007791 Offset += RHS->getZExtValue();
7792 Scale = SubScale;
7793 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007794 }
7795 }
7796 }
7797
7798 // Otherwise, we can't look past this.
7799 Scale = 1;
7800 Offset = 0;
7801 return Val;
7802}
7803
7804
Chris Lattnerb3f83972005-10-24 06:03:58 +00007805/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7806/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007807Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007808 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007809 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007810
Chris Lattnerb53c2382005-10-24 06:22:12 +00007811 // Remove any uses of AI that are dead.
7812 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007813
Chris Lattnerb53c2382005-10-24 06:22:12 +00007814 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7815 Instruction *User = cast<Instruction>(*UI++);
7816 if (isInstructionTriviallyDead(User)) {
7817 while (UI != E && *UI == User)
7818 ++UI; // If this instruction uses AI more than once, don't break UI.
7819
Chris Lattnerb53c2382005-10-24 06:22:12 +00007820 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007821 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007822 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007823 }
7824 }
7825
Chris Lattnerb3f83972005-10-24 06:03:58 +00007826 // Get the type really allocated and the type casted to.
7827 const Type *AllocElTy = AI.getAllocatedType();
7828 const Type *CastElTy = PTy->getElementType();
7829 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007830
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007831 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7832 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007833 if (CastElTyAlign < AllocElTyAlign) return 0;
7834
Chris Lattner39387a52005-10-24 06:35:18 +00007835 // If the allocation has multiple uses, only promote it if we are strictly
7836 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007837 // same, we open the door to infinite loops of various kinds. (A reference
7838 // from a dbg.declare doesn't count as a use for this purpose.)
7839 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7840 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007841
Duncan Sands777d2302009-05-09 07:06:46 +00007842 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7843 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007844 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007845
Chris Lattner455fcc82005-10-29 03:19:53 +00007846 // See if we can satisfy the modulus by pulling a scale out of the array
7847 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007848 unsigned ArraySizeScale;
7849 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007850 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007851 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7852 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007853
Chris Lattner455fcc82005-10-29 03:19:53 +00007854 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7855 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007856 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7857 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007858
Chris Lattner455fcc82005-10-29 03:19:53 +00007859 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7860 Value *Amt = 0;
7861 if (Scale == 1) {
7862 Amt = NumElements;
7863 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007864 // If the allocation size is constant, form a constant mul expression
Owen Andersond672ecb2009-07-03 00:17:18 +00007865 Amt = Context->getConstantInt(Type::Int32Ty, Scale);
Reid Spencerc5b206b2006-12-31 05:48:39 +00007866 if (isa<ConstantInt>(NumElements))
Owen Andersond672ecb2009-07-03 00:17:18 +00007867 Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
Dan Gohman6de29f82009-06-15 22:12:54 +00007868 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007869 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007870 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007871 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007872 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007873 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007874 }
7875
Jeff Cohen86796be2007-04-04 16:58:57 +00007876 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007877 Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007878 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007879 Amt = InsertNewInstBefore(Tmp, AI);
7880 }
7881
Chris Lattnerb3f83972005-10-24 06:03:58 +00007882 AllocationInst *New;
7883 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +00007884 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007885 else
Owen Anderson50dead02009-07-15 23:53:25 +00007886 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007887 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007888 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007889
Dale Johannesena0a66372009-03-05 00:39:02 +00007890 // If the allocation has one real use plus a dbg.declare, just remove the
7891 // declare.
7892 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7893 EraseInstFromFunction(*DI);
7894 }
7895 // If the allocation has multiple real uses, insert a cast and change all
7896 // things that used it to use the new cast. This will also hack on CI, but it
7897 // will die soon.
7898 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007899 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007900 // New is the allocation instruction, pointer typed. AI is the original
7901 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7902 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007903 InsertNewInstBefore(NewCast, AI);
7904 AI.replaceAllUsesWith(NewCast);
7905 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007906 return ReplaceInstUsesWith(CI, New);
7907}
7908
Chris Lattner70074e02006-05-13 02:06:03 +00007909/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007910/// and return it as type Ty without inserting any new casts and without
7911/// changing the computed value. This is used by code that tries to decide
7912/// whether promoting or shrinking integer operations to wider or smaller types
7913/// will allow us to eliminate a truncate or extend.
7914///
7915/// This is a truncation operation if Ty is smaller than V->getType(), or an
7916/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007917///
7918/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7919/// should return true if trunc(V) can be computed by computing V in the smaller
7920/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7921/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7922/// efficiently truncated.
7923///
7924/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7925/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7926/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007927bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007928 unsigned CastOpc,
7929 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007930 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007931 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007932 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007933
7934 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007935 if (!I) return false;
7936
Dan Gohman6de29f82009-06-15 22:12:54 +00007937 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007938
Chris Lattner951626b2007-08-02 06:11:14 +00007939 // If this is an extension or truncate, we can often eliminate it.
7940 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7941 // If this is a cast from the destination type, we can trivially eliminate
7942 // it, and this will remove a cast overall.
7943 if (I->getOperand(0)->getType() == Ty) {
7944 // If the first operand is itself a cast, and is eliminable, do not count
7945 // this as an eliminable cast. We would prefer to eliminate those two
7946 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007947 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007948 ++NumCastsRemoved;
7949 return true;
7950 }
7951 }
7952
7953 // We can't extend or shrink something that has multiple uses: doing so would
7954 // require duplicating the instruction in general, which isn't profitable.
7955 if (!I->hasOneUse()) return false;
7956
Evan Chengf35fd542009-01-15 17:01:23 +00007957 unsigned Opc = I->getOpcode();
7958 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007959 case Instruction::Add:
7960 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007961 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007962 case Instruction::And:
7963 case Instruction::Or:
7964 case Instruction::Xor:
7965 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007966 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007967 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007968 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007969 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007970
Eli Friedman070a9812009-07-13 22:46:01 +00007971 case Instruction::UDiv:
7972 case Instruction::URem: {
7973 // UDiv and URem can be truncated if all the truncated bits are zero.
7974 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7975 uint32_t BitWidth = Ty->getScalarSizeInBits();
7976 if (BitWidth < OrigBitWidth) {
7977 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7978 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7979 MaskedValueIsZero(I->getOperand(1), Mask)) {
7980 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7981 NumCastsRemoved) &&
7982 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7983 NumCastsRemoved);
7984 }
7985 }
7986 break;
7987 }
Chris Lattner46b96052006-11-29 07:18:39 +00007988 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007989 // If we are truncating the result of this SHL, and if it's a shift of a
7990 // constant amount, we can always perform a SHL in a smaller type.
7991 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007992 uint32_t BitWidth = Ty->getScalarSizeInBits();
7993 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007994 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007995 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007996 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007997 }
7998 break;
7999 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008000 // If this is a truncate of a logical shr, we can truncate it to a smaller
8001 // lshr iff we know that the bits we would otherwise be shifting in are
8002 // already zeros.
8003 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008004 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8005 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008006 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008007 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008008 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8009 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008010 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008011 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008012 }
8013 }
Chris Lattner46b96052006-11-29 07:18:39 +00008014 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008015 case Instruction::ZExt:
8016 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008017 case Instruction::Trunc:
8018 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008019 // can safely replace it. Note that replacing it does not reduce the number
8020 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008021 if (Opc == CastOpc)
8022 return true;
8023
8024 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008025 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008026 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008027 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008028 case Instruction::Select: {
8029 SelectInst *SI = cast<SelectInst>(I);
8030 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008031 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008032 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008033 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008034 }
Chris Lattner8114b712008-06-18 04:00:49 +00008035 case Instruction::PHI: {
8036 // We can change a phi if we can change all operands.
8037 PHINode *PN = cast<PHINode>(I);
8038 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8039 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008040 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008041 return false;
8042 return true;
8043 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008044 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008045 // TODO: Can handle more cases here.
8046 break;
8047 }
8048
8049 return false;
8050}
8051
8052/// EvaluateInDifferentType - Given an expression that
8053/// CanEvaluateInDifferentType returns true for, actually insert the code to
8054/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008055Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008056 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008057 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +00008058 return Context->getConstantExprIntegerCast(C, Ty,
8059 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008060
8061 // Otherwise, it must be an instruction.
8062 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008063 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008064 unsigned Opc = I->getOpcode();
8065 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008066 case Instruction::Add:
8067 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008068 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008069 case Instruction::And:
8070 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008071 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008072 case Instruction::AShr:
8073 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008074 case Instruction::Shl:
8075 case Instruction::UDiv:
8076 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008077 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008078 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008079 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008080 break;
8081 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008082 case Instruction::Trunc:
8083 case Instruction::ZExt:
8084 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008085 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008086 // just return the source. There's no need to insert it because it is not
8087 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008088 if (I->getOperand(0)->getType() == Ty)
8089 return I->getOperand(0);
8090
Chris Lattner8114b712008-06-18 04:00:49 +00008091 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008092 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008093 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008094 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008095 case Instruction::Select: {
8096 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8097 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8098 Res = SelectInst::Create(I->getOperand(0), True, False);
8099 break;
8100 }
Chris Lattner8114b712008-06-18 04:00:49 +00008101 case Instruction::PHI: {
8102 PHINode *OPN = cast<PHINode>(I);
8103 PHINode *NPN = PHINode::Create(Ty);
8104 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8105 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8106 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8107 }
8108 Res = NPN;
8109 break;
8110 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008111 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008112 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008113 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008114 break;
8115 }
8116
Chris Lattner8114b712008-06-18 04:00:49 +00008117 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008118 return InsertNewInstBefore(Res, *I);
8119}
8120
Reid Spencer3da59db2006-11-27 01:05:10 +00008121/// @brief Implement the transforms common to all CastInst visitors.
8122Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008123 Value *Src = CI.getOperand(0);
8124
Dan Gohman23d9d272007-05-11 21:10:54 +00008125 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008126 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008127 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008128 if (Instruction::CastOps opc =
8129 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8130 // The first cast (CSrc) is eliminable so we need to fix up or replace
8131 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008132 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008133 }
8134 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008135
Reid Spencer3da59db2006-11-27 01:05:10 +00008136 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008137 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8138 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8139 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008140
8141 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008142 if (isa<PHINode>(Src))
8143 if (Instruction *NV = FoldOpIntoPhi(CI))
8144 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008145
Reid Spencer3da59db2006-11-27 01:05:10 +00008146 return 0;
8147}
8148
Chris Lattner46cd5a12009-01-09 05:44:56 +00008149/// FindElementAtOffset - Given a type and a constant offset, determine whether
8150/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008151/// the specified offset. If so, fill them into NewIndices and return the
8152/// resultant element type, otherwise return null.
8153static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8154 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008155 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008156 LLVMContext *Context) {
Chris Lattner3914f722009-01-24 01:00:13 +00008157 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008158
8159 // Start with the index over the outer type. Note that the type size
8160 // might be zero (even if the offset isn't zero) if the indexed type
8161 // is something like [0 x {int, int}]
8162 const Type *IntPtrTy = TD->getIntPtrType();
8163 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008164 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008165 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008166 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008167
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008168 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008169 if (Offset < 0) {
8170 --FirstIdx;
8171 Offset += TySize;
8172 assert(Offset >= 0);
8173 }
8174 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8175 }
8176
Owen Andersond672ecb2009-07-03 00:17:18 +00008177 NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008178
8179 // Index into the types. If we fail, set OrigBase to null.
8180 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008181 // Indexing into tail padding between struct/array elements.
8182 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008183 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008184
Chris Lattner46cd5a12009-01-09 05:44:56 +00008185 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8186 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008187 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8188 "Offset must stay within the indexed type");
8189
Chris Lattner46cd5a12009-01-09 05:44:56 +00008190 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Andersond672ecb2009-07-03 00:17:18 +00008191 NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008192
8193 Offset -= SL->getElementOffset(Elt);
8194 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008195 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008196 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008197 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersond672ecb2009-07-03 00:17:18 +00008198 NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008199 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008200 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008201 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008202 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008203 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008204 }
8205 }
8206
Chris Lattner3914f722009-01-24 01:00:13 +00008207 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008208}
8209
Chris Lattnerd3e28342007-04-27 17:44:50 +00008210/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8211Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8212 Value *Src = CI.getOperand(0);
8213
Chris Lattnerd3e28342007-04-27 17:44:50 +00008214 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008215 // If casting the result of a getelementptr instruction with no offset, turn
8216 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008217 if (GEP->hasAllZeroIndices()) {
8218 // Changing the cast operand is usually not a good idea but it is safe
8219 // here because the pointer operand is being replaced with another
8220 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00008221 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008222 CI.setOperand(0, GEP->getOperand(0));
8223 return &CI;
8224 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008225
8226 // If the GEP has a single use, and the base pointer is a bitcast, and the
8227 // GEP computes a constant offset, see if we can convert these three
8228 // instructions into fewer. This typically happens with unions and other
8229 // non-type-safe code.
8230 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8231 if (GEP->hasAllConstantIndices()) {
8232 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008233 ConstantInt *OffsetV =
8234 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008235 int64_t Offset = OffsetV->getSExtValue();
8236
8237 // Get the base pointer input of the bitcast, and the type it points to.
8238 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8239 const Type *GEPIdxTy =
8240 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008241 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008242 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008243 // If we were able to index down into an element, create the GEP
8244 // and bitcast the result. This eliminates one bitcast, potentially
8245 // two.
8246 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8247 NewIndices.begin(),
8248 NewIndices.end(), "");
8249 InsertNewInstBefore(NGEP, CI);
8250 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008251
Chris Lattner46cd5a12009-01-09 05:44:56 +00008252 if (isa<BitCastInst>(CI))
8253 return new BitCastInst(NGEP, CI.getType());
8254 assert(isa<PtrToIntInst>(CI));
8255 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008256 }
8257 }
8258 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008259 }
8260
8261 return commonCastTransforms(CI);
8262}
8263
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008264/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8265/// type like i42. We don't want to introduce operations on random non-legal
8266/// integer types where they don't already exist in the code. In the future,
8267/// we should consider making this based off target-data, so that 32-bit targets
8268/// won't get i64 operations etc.
8269static bool isSafeIntegerType(const Type *Ty) {
8270 switch (Ty->getPrimitiveSizeInBits()) {
8271 case 8:
8272 case 16:
8273 case 32:
8274 case 64:
8275 return true;
8276 default:
8277 return false;
8278 }
8279}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008280
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008281/// commonIntCastTransforms - This function implements the common transforms
8282/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008283Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8284 if (Instruction *Result = commonCastTransforms(CI))
8285 return Result;
8286
8287 Value *Src = CI.getOperand(0);
8288 const Type *SrcTy = Src->getType();
8289 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008290 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8291 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008292
Reid Spencer3da59db2006-11-27 01:05:10 +00008293 // See if we can simplify any instructions used by the LHS whose sole
8294 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008295 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008296 return &CI;
8297
8298 // If the source isn't an instruction or has more than one use then we
8299 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008300 Instruction *SrcI = dyn_cast<Instruction>(Src);
8301 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008302 return 0;
8303
Chris Lattnerc739cd62007-03-03 05:27:34 +00008304 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008305 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008306 // Only do this if the dest type is a simple type, don't convert the
8307 // expression tree to something weird like i93 unless the source is also
8308 // strange.
8309 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008310 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8311 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008312 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008313 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008314 // eliminates the cast, so it is always a win. If this is a zero-extension,
8315 // we need to do an AND to maintain the clear top-part of the computation,
8316 // so we require that the input have eliminated at least one cast. If this
8317 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008318 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008319 bool DoXForm = false;
8320 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008321 switch (CI.getOpcode()) {
8322 default:
8323 // All the others use floating point so we shouldn't actually
8324 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008325 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008326 case Instruction::Trunc:
8327 DoXForm = true;
8328 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008329 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008330 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008331 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008332 // If it's unnecessary to issue an AND to clear the high bits, it's
8333 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008334 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008335 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8336 if (MaskedValueIsZero(TryRes, Mask))
8337 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008338
8339 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008340 if (TryI->use_empty())
8341 EraseInstFromFunction(*TryI);
8342 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008343 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008344 }
Evan Chengf35fd542009-01-15 17:01:23 +00008345 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008346 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008347 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008348 // If we do not have to emit the truncate + sext pair, then it's always
8349 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008350 //
8351 // It's not safe to eliminate the trunc + sext pair if one of the
8352 // eliminated cast is a truncate. e.g.
8353 // t2 = trunc i32 t1 to i16
8354 // t3 = sext i16 t2 to i32
8355 // !=
8356 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008357 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008358 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8359 if (NumSignBits > (DestBitSize - SrcBitSize))
8360 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008361
8362 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008363 if (TryI->use_empty())
8364 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008365 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008366 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008367 }
Evan Chengf35fd542009-01-15 17:01:23 +00008368 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008369
8370 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008371 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8372 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008373 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8374 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008375 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008376 // Just replace this cast with the result.
8377 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008378
Reid Spencer3da59db2006-11-27 01:05:10 +00008379 assert(Res->getType() == DestTy);
8380 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008381 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008382 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008383 // Just replace this cast with the result.
8384 return ReplaceInstUsesWith(CI, Res);
8385 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008386 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008387
8388 // If the high bits are already zero, just replace this cast with the
8389 // result.
8390 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8391 if (MaskedValueIsZero(Res, Mask))
8392 return ReplaceInstUsesWith(CI, Res);
8393
8394 // We need to emit an AND to clear the high bits.
Owen Andersond672ecb2009-07-03 00:17:18 +00008395 Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
Chris Lattnercd1d6d52007-04-02 05:48:58 +00008396 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008397 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008398 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008399 case Instruction::SExt: {
8400 // If the high bits are already filled with sign bit, just replace this
8401 // cast with the result.
8402 unsigned NumSignBits = ComputeNumSignBits(Res);
8403 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008404 return ReplaceInstUsesWith(CI, Res);
8405
Reid Spencer3da59db2006-11-27 01:05:10 +00008406 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008407 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008408 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8409 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008410 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008411 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008412 }
8413 }
8414
8415 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8416 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8417
8418 switch (SrcI->getOpcode()) {
8419 case Instruction::Add:
8420 case Instruction::Mul:
8421 case Instruction::And:
8422 case Instruction::Or:
8423 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008424 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008425 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8426 // Don't insert two casts unless at least one can be eliminated.
8427 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008428 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman65445c52009-07-13 21:45:57 +00008429 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8430 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008431 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008432 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008433 }
8434 }
8435
8436 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8437 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8438 SrcI->getOpcode() == Instruction::Xor &&
Owen Andersond672ecb2009-07-03 00:17:18 +00008439 Op1 == Context->getConstantIntTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008440 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008441 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008442 return BinaryOperator::CreateXor(New,
8443 Context->getConstantInt(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008444 }
8445 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008446
Eli Friedman65445c52009-07-13 21:45:57 +00008447 case Instruction::Shl: {
8448 // Canonicalize trunc inside shl, if we can.
8449 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8450 if (CI && DestBitSize < SrcBitSize &&
8451 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8452 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8453 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008454 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008455 }
8456 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008457 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008458 }
8459 return 0;
8460}
8461
Chris Lattner8a9f5712007-04-11 06:57:46 +00008462Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008463 if (Instruction *Result = commonIntCastTransforms(CI))
8464 return Result;
8465
8466 Value *Src = CI.getOperand(0);
8467 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008468 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8469 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008470
8471 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00008472 if (DestBitWidth == 1 &&
8473 isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008474 Constant *One = Context->getConstantInt(Src->getType(), 1);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008475 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008476 Value *Zero = Context->getNullValue(Src->getType());
Owen Anderson333c4002009-07-09 23:48:35 +00008477 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008478 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008479
Chris Lattner4f9797d2009-03-24 18:15:30 +00008480 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8481 ConstantInt *ShAmtV = 0;
8482 Value *ShiftOp = 0;
8483 if (Src->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008484 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008485 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8486
8487 // Get a mask for the bits shifting in.
8488 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8489 if (MaskedValueIsZero(ShiftOp, Mask)) {
8490 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersond672ecb2009-07-03 00:17:18 +00008491 return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008492
8493 // Okay, we can shrink this. Truncate the input, then return a new
8494 // shift.
8495 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008496 Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008497 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008498 }
8499 }
8500
8501 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008502}
8503
Evan Chengb98a10e2008-03-24 00:21:34 +00008504/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8505/// in order to eliminate the icmp.
8506Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8507 bool DoXform) {
8508 // If we are just checking for a icmp eq of a single bit and zext'ing it
8509 // to an integer, then shift the bit to the appropriate place and then
8510 // cast to integer to avoid the comparison.
8511 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8512 const APInt &Op1CV = Op1C->getValue();
8513
8514 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8515 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8516 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8517 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8518 if (!DoXform) return ICI;
8519
8520 Value *In = ICI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00008521 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008522 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008523 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008524 In->getName()+".lobit"),
8525 CI);
8526 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008527 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008528 false/*ZExt*/, "tmp", &CI);
8529
8530 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008531 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008532 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008533 In->getName()+".not"),
8534 CI);
8535 }
8536
8537 return ReplaceInstUsesWith(CI, In);
8538 }
8539
8540
8541
8542 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8543 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8544 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8545 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8546 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8547 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8548 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8549 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8550 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8551 // This only works for EQ and NE
8552 ICI->isEquality()) {
8553 // If Op1C some other power of two, convert:
8554 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8555 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8556 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8557 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8558
8559 APInt KnownZeroMask(~KnownZero);
8560 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8561 if (!DoXform) return ICI;
8562
8563 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8564 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8565 // (X&4) == 2 --> false
8566 // (X&4) != 2 --> true
Owen Andersond672ecb2009-07-03 00:17:18 +00008567 Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8568 Res = Context->getConstantExprZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008569 return ReplaceInstUsesWith(CI, Res);
8570 }
8571
8572 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8573 Value *In = ICI->getOperand(0);
8574 if (ShiftAmt) {
8575 // Perform a logical shr by shiftamt.
8576 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008577 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersond672ecb2009-07-03 00:17:18 +00008578 Context->getConstantInt(In->getType(), ShiftAmt),
Evan Chengb98a10e2008-03-24 00:21:34 +00008579 In->getName()+".lobit"), CI);
8580 }
8581
8582 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersond672ecb2009-07-03 00:17:18 +00008583 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008584 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008585 InsertNewInstBefore(cast<Instruction>(In), CI);
8586 }
8587
8588 if (CI.getType() == In->getType())
8589 return ReplaceInstUsesWith(CI, In);
8590 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008591 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008592 }
8593 }
8594 }
8595
8596 return 0;
8597}
8598
Chris Lattner8a9f5712007-04-11 06:57:46 +00008599Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008600 // If one of the common conversion will work ..
8601 if (Instruction *Result = commonIntCastTransforms(CI))
8602 return Result;
8603
8604 Value *Src = CI.getOperand(0);
8605
Chris Lattnera84f47c2009-02-17 20:47:23 +00008606 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8607 // types and if the sizes are just right we can convert this into a logical
8608 // 'and' which will be much cheaper than the pair of casts.
8609 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8610 // Get the sizes of the types involved. We know that the intermediate type
8611 // will be smaller than A or C, but don't know the relation between A and C.
8612 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008613 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8614 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8615 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008616 // If we're actually extending zero bits, then if
8617 // SrcSize < DstSize: zext(a & mask)
8618 // SrcSize == DstSize: a & mask
8619 // SrcSize > DstSize: trunc(a) & mask
8620 if (SrcSize < DstSize) {
8621 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008622 Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008623 Instruction *And =
8624 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8625 InsertNewInstBefore(And, CI);
8626 return new ZExtInst(And, CI.getType());
8627 } else if (SrcSize == DstSize) {
8628 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008629 return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008630 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008631 } else if (SrcSize > DstSize) {
8632 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8633 InsertNewInstBefore(Trunc, CI);
8634 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008635 return BinaryOperator::CreateAnd(Trunc,
8636 Context->getConstantInt(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008637 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008638 }
8639 }
8640
Evan Chengb98a10e2008-03-24 00:21:34 +00008641 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8642 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008643
Evan Chengb98a10e2008-03-24 00:21:34 +00008644 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8645 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8646 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8647 // of the (zext icmp) will be transformed.
8648 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8649 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8650 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8651 (transformZExtICmp(LHS, CI, false) ||
8652 transformZExtICmp(RHS, CI, false))) {
8653 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8654 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008655 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008656 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008657 }
8658
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008659 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008660 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8661 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8662 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8663 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008664 if (TI0->getType() == CI.getType())
8665 return
8666 BinaryOperator::CreateAnd(TI0,
Owen Andersond672ecb2009-07-03 00:17:18 +00008667 Context->getConstantExprZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008668 }
8669
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008670 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8671 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8672 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8673 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8674 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8675 And->getOperand(1) == C)
8676 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8677 Value *TI0 = TI->getOperand(0);
8678 if (TI0->getType() == CI.getType()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008679 Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008680 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8681 InsertNewInstBefore(NewAnd, *And);
8682 return BinaryOperator::CreateXor(NewAnd, ZC);
8683 }
8684 }
8685
Reid Spencer3da59db2006-11-27 01:05:10 +00008686 return 0;
8687}
8688
Chris Lattner8a9f5712007-04-11 06:57:46 +00008689Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008690 if (Instruction *I = commonIntCastTransforms(CI))
8691 return I;
8692
Chris Lattner8a9f5712007-04-11 06:57:46 +00008693 Value *Src = CI.getOperand(0);
8694
Dan Gohman1975d032008-10-30 20:40:10 +00008695 // Canonicalize sign-extend from i1 to a select.
8696 if (Src->getType() == Type::Int1Ty)
8697 return SelectInst::Create(Src,
Owen Anderson73c6b712009-07-13 20:58:05 +00008698 Context->getAllOnesValue(CI.getType()),
Owen Andersond672ecb2009-07-03 00:17:18 +00008699 Context->getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008700
8701 // See if the value being truncated is already sign extended. If so, just
8702 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008703 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008704 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008705 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8706 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8707 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008708 unsigned NumSignBits = ComputeNumSignBits(Op);
8709
8710 if (OpBits == DestBits) {
8711 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8712 // bits, it is already ready.
8713 if (NumSignBits > DestBits-MidBits)
8714 return ReplaceInstUsesWith(CI, Op);
8715 } else if (OpBits < DestBits) {
8716 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8717 // bits, just sext from i32.
8718 if (NumSignBits > OpBits-MidBits)
8719 return new SExtInst(Op, CI.getType(), "tmp");
8720 } else {
8721 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8722 // bits, just truncate to i32.
8723 if (NumSignBits > OpBits-MidBits)
8724 return new TruncInst(Op, CI.getType(), "tmp");
8725 }
8726 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008727
8728 // If the input is a shl/ashr pair of a same constant, then this is a sign
8729 // extension from a smaller value. If we could trust arbitrary bitwidth
8730 // integers, we could turn this into a truncate to the smaller bit and then
8731 // use a sext for the whole extension. Since we don't, look deeper and check
8732 // for a truncate. If the source and dest are the same type, eliminate the
8733 // trunc and extend and just do shifts. For example, turn:
8734 // %a = trunc i32 %i to i8
8735 // %b = shl i8 %a, 6
8736 // %c = ashr i8 %b, 6
8737 // %d = sext i8 %c to i32
8738 // into:
8739 // %a = shl i32 %i, 30
8740 // %d = ashr i32 %a, 30
8741 Value *A = 0;
8742 ConstantInt *BA = 0, *CA = 0;
8743 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008744 m_ConstantInt(CA)), *Context) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008745 BA == CA && isa<TruncInst>(A)) {
8746 Value *I = cast<TruncInst>(A)->getOperand(0);
8747 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008748 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8749 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008750 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersond672ecb2009-07-03 00:17:18 +00008751 Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
Chris Lattner46bbad22008-08-06 07:35:52 +00008752 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8753 CI.getName()), CI);
8754 return BinaryOperator::CreateAShr(I, ShAmtV);
8755 }
8756 }
8757
Chris Lattnerba417832007-04-11 06:12:58 +00008758 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008759}
8760
Chris Lattnerb7530652008-01-27 05:29:54 +00008761/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8762/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008763static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008764 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008765 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008766 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008767 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8768 if (!losesInfo)
Owen Andersond672ecb2009-07-03 00:17:18 +00008769 return Context->getConstantFP(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008770 return 0;
8771}
8772
8773/// LookThroughFPExtensions - If this is an fp extension instruction, look
8774/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008775static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008776 if (Instruction *I = dyn_cast<Instruction>(V))
8777 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008778 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008779
8780 // If this value is a constant, return the constant in the smallest FP type
8781 // that can accurately represent it. This allows us to turn
8782 // (float)((double)X+2.0) into x+2.0f.
8783 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8784 if (CFP->getType() == Type::PPC_FP128Ty)
8785 return V; // No constant folding of this.
8786 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008787 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008788 return V;
8789 if (CFP->getType() == Type::DoubleTy)
8790 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008791 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008792 return V;
8793 // Don't try to shrink to various long double types.
8794 }
8795
8796 return V;
8797}
8798
8799Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8800 if (Instruction *I = commonCastTransforms(CI))
8801 return I;
8802
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008803 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008804 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008805 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008806 // many builtins (sqrt, etc).
8807 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8808 if (OpI && OpI->hasOneUse()) {
8809 switch (OpI->getOpcode()) {
8810 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008811 case Instruction::FAdd:
8812 case Instruction::FSub:
8813 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008814 case Instruction::FDiv:
8815 case Instruction::FRem:
8816 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008817 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8818 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008819 if (LHSTrunc->getType() != SrcTy &&
8820 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008821 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008822 // If the source types were both smaller than the destination type of
8823 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008824 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8825 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008826 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8827 CI.getType(), CI);
8828 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8829 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008830 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008831 }
8832 }
8833 break;
8834 }
8835 }
8836 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008837}
8838
8839Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8840 return commonCastTransforms(CI);
8841}
8842
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008843Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008844 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8845 if (OpI == 0)
8846 return commonCastTransforms(FI);
8847
8848 // fptoui(uitofp(X)) --> X
8849 // fptoui(sitofp(X)) --> X
8850 // This is safe if the intermediate type has enough bits in its mantissa to
8851 // accurately represent all values of X. For example, do not do this with
8852 // i64->float->i64. This is also safe for sitofp case, because any negative
8853 // 'X' value would cause an undefined result for the fptoui.
8854 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8855 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008856 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008857 OpI->getType()->getFPMantissaWidth())
8858 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008859
8860 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008861}
8862
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008863Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008864 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8865 if (OpI == 0)
8866 return commonCastTransforms(FI);
8867
8868 // fptosi(sitofp(X)) --> X
8869 // fptosi(uitofp(X)) --> X
8870 // This is safe if the intermediate type has enough bits in its mantissa to
8871 // accurately represent all values of X. For example, do not do this with
8872 // i64->float->i64. This is also safe for sitofp case, because any negative
8873 // 'X' value would cause an undefined result for the fptoui.
8874 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8875 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008876 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008877 OpI->getType()->getFPMantissaWidth())
8878 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008879
8880 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008881}
8882
8883Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8884 return commonCastTransforms(CI);
8885}
8886
8887Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8888 return commonCastTransforms(CI);
8889}
8890
Chris Lattnera0e69692009-03-24 18:35:40 +00008891Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8892 // If the destination integer type is smaller than the intptr_t type for
8893 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8894 // trunc to be exposed to other transforms. Don't do this for extending
8895 // ptrtoint's, because we don't know if the target sign or zero extends its
8896 // pointers.
Dan Gohman6de29f82009-06-15 22:12:54 +00008897 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008898 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8899 TD->getIntPtrType(),
8900 "tmp"), CI);
8901 return new TruncInst(P, CI.getType());
8902 }
8903
Chris Lattnerd3e28342007-04-27 17:44:50 +00008904 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008905}
8906
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008907Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008908 // If the source integer type is larger than the intptr_t type for
8909 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8910 // allows the trunc to be exposed to other transforms. Don't do this for
8911 // extending inttoptr's, because we don't know if the target sign or zero
8912 // extends to pointers.
Dan Gohman6de29f82009-06-15 22:12:54 +00008913 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008914 TD->getPointerSizeInBits()) {
8915 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8916 TD->getIntPtrType(),
8917 "tmp"), CI);
8918 return new IntToPtrInst(P, CI.getType());
8919 }
8920
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008921 if (Instruction *I = commonCastTransforms(CI))
8922 return I;
8923
8924 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8925 if (!DestPointee->isSized()) return 0;
8926
8927 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8928 ConstantInt *Cst;
8929 Value *X;
8930 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008931 m_ConstantInt(Cst)), *Context)) {
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008932 // If the source and destination operands have the same type, see if this
8933 // is a single-index GEP.
8934 if (X->getType() == CI.getType()) {
8935 // Get the size of the pointee type.
Duncan Sands777d2302009-05-09 07:06:46 +00008936 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008937
8938 // Convert the constant to intptr type.
8939 APInt Offset = Cst->getValue();
8940 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8941
8942 // If Offset is evenly divisible by Size, we can do this xform.
8943 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8944 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Owen Andersond672ecb2009-07-03 00:17:18 +00008945 return GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008946 }
8947 }
8948 // TODO: Could handle other cases, e.g. where add is indexing into field of
8949 // struct etc.
8950 } else if (CI.getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008951 match(CI.getOperand(0), m_Add(m_Value(X),
8952 m_ConstantInt(Cst)), *Context)) {
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008953 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8954 // "inttoptr+GEP" instead of "add+intptr".
8955
8956 // Get the size of the pointee type.
Duncan Sands777d2302009-05-09 07:06:46 +00008957 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008958
8959 // Convert the constant to intptr type.
8960 APInt Offset = Cst->getValue();
8961 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8962
8963 // If Offset is evenly divisible by Size, we can do this xform.
8964 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8965 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8966
8967 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8968 "tmp"), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008969 return GetElementPtrInst::Create(P,
8970 Context->getConstantInt(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008971 }
8972 }
8973 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008974}
8975
Chris Lattnerd3e28342007-04-27 17:44:50 +00008976Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008977 // If the operands are integer typed then apply the integer transforms,
8978 // otherwise just apply the common ones.
8979 Value *Src = CI.getOperand(0);
8980 const Type *SrcTy = Src->getType();
8981 const Type *DestTy = CI.getType();
8982
Eli Friedman7e25d452009-07-13 20:53:00 +00008983 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008984 if (Instruction *I = commonPointerCastTransforms(CI))
8985 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008986 } else {
8987 if (Instruction *Result = commonCastTransforms(CI))
8988 return Result;
8989 }
8990
8991
8992 // Get rid of casts from one type to the same type. These are useless and can
8993 // be replaced by the operand.
8994 if (DestTy == Src->getType())
8995 return ReplaceInstUsesWith(CI, Src);
8996
Reid Spencer3da59db2006-11-27 01:05:10 +00008997 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008998 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8999 const Type *DstElTy = DstPTy->getElementType();
9000 const Type *SrcElTy = SrcPTy->getElementType();
9001
Nate Begeman83ad90a2008-03-31 00:22:16 +00009002 // If the address spaces don't match, don't eliminate the bitcast, which is
9003 // required for changing types.
9004 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9005 return 0;
9006
Chris Lattnerd3e28342007-04-27 17:44:50 +00009007 // If we are casting a malloc or alloca to a pointer to a type of the same
9008 // size, rewrite the allocation instruction to allocate the "right" type.
9009 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9010 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9011 return V;
9012
Chris Lattnerd717c182007-05-05 22:32:24 +00009013 // If the source and destination are pointers, and this cast is equivalent
9014 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00009015 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Andersond672ecb2009-07-03 00:17:18 +00009016 Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
Chris Lattnerd3e28342007-04-27 17:44:50 +00009017 unsigned NumZeros = 0;
9018 while (SrcElTy != DstElTy &&
9019 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9020 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9021 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9022 ++NumZeros;
9023 }
Chris Lattner4e998b22004-09-29 05:07:12 +00009024
Chris Lattnerd3e28342007-04-27 17:44:50 +00009025 // If we found a path from the src to dest, create the getelementptr now.
9026 if (SrcElTy == DstElTy) {
9027 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00009028 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
9029 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00009030 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009031 }
Chris Lattner24c8e382003-07-24 17:35:25 +00009032
Reid Spencer3da59db2006-11-27 01:05:10 +00009033 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9034 if (SVI->hasOneUse()) {
9035 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9036 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009037 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009038 cast<VectorType>(DestTy)->getNumElements() ==
9039 SVI->getType()->getNumElements() &&
9040 SVI->getType()->getNumElements() ==
9041 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009042 CastInst *Tmp;
9043 // If either of the operands is a cast from CI.getType(), then
9044 // evaluating the shuffle in the casted destination's type will allow
9045 // us to eliminate at least one cast.
9046 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9047 Tmp->getOperand(0)->getType() == DestTy) ||
9048 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9049 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009050 Value *LHS = InsertCastBefore(Instruction::BitCast,
9051 SVI->getOperand(0), DestTy, CI);
9052 Value *RHS = InsertCastBefore(Instruction::BitCast,
9053 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009054 // Return a new shuffle vector. Use the same element ID's, as we
9055 // know the vector types match #elts.
9056 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009057 }
9058 }
9059 }
9060 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009061 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009062}
9063
Chris Lattnere576b912004-04-09 23:46:01 +00009064/// GetSelectFoldableOperands - We want to turn code that looks like this:
9065/// %C = or %A, %B
9066/// %D = select %cond, %C, %A
9067/// into:
9068/// %C = select %cond, %B, 0
9069/// %D = or %A, %C
9070///
9071/// Assuming that the specified instruction is an operand to the select, return
9072/// a bitmask indicating which operands of this instruction are foldable if they
9073/// equal the other incoming value of the select.
9074///
9075static unsigned GetSelectFoldableOperands(Instruction *I) {
9076 switch (I->getOpcode()) {
9077 case Instruction::Add:
9078 case Instruction::Mul:
9079 case Instruction::And:
9080 case Instruction::Or:
9081 case Instruction::Xor:
9082 return 3; // Can fold through either operand.
9083 case Instruction::Sub: // Can only fold on the amount subtracted.
9084 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009085 case Instruction::LShr:
9086 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009087 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009088 default:
9089 return 0; // Cannot fold
9090 }
9091}
9092
9093/// GetSelectFoldableConstant - For the same transformation as the previous
9094/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009095static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009096 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009097 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009098 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009099 case Instruction::Add:
9100 case Instruction::Sub:
9101 case Instruction::Or:
9102 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009103 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009104 case Instruction::LShr:
9105 case Instruction::AShr:
Owen Andersond672ecb2009-07-03 00:17:18 +00009106 return Context->getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009107 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00009108 return Context->getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009109 case Instruction::Mul:
Owen Andersond672ecb2009-07-03 00:17:18 +00009110 return Context->getConstantInt(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009111 }
9112}
9113
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009114/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9115/// have the same opcode and only one use each. Try to simplify this.
9116Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9117 Instruction *FI) {
9118 if (TI->getNumOperands() == 1) {
9119 // If this is a non-volatile load or a cast from the same type,
9120 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009121 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009122 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9123 return 0;
9124 } else {
9125 return 0; // unknown unary op.
9126 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009127
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009128 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009129 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9130 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009131 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009132 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009133 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009134 }
9135
Reid Spencer832254e2007-02-02 02:16:23 +00009136 // Only handle binary operators here.
9137 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009138 return 0;
9139
9140 // Figure out if the operations have any operands in common.
9141 Value *MatchOp, *OtherOpT, *OtherOpF;
9142 bool MatchIsOpZero;
9143 if (TI->getOperand(0) == FI->getOperand(0)) {
9144 MatchOp = TI->getOperand(0);
9145 OtherOpT = TI->getOperand(1);
9146 OtherOpF = FI->getOperand(1);
9147 MatchIsOpZero = true;
9148 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9149 MatchOp = TI->getOperand(1);
9150 OtherOpT = TI->getOperand(0);
9151 OtherOpF = FI->getOperand(0);
9152 MatchIsOpZero = false;
9153 } else if (!TI->isCommutative()) {
9154 return 0;
9155 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9156 MatchOp = TI->getOperand(0);
9157 OtherOpT = TI->getOperand(1);
9158 OtherOpF = FI->getOperand(0);
9159 MatchIsOpZero = true;
9160 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9161 MatchOp = TI->getOperand(1);
9162 OtherOpT = TI->getOperand(0);
9163 OtherOpF = FI->getOperand(1);
9164 MatchIsOpZero = true;
9165 } else {
9166 return 0;
9167 }
9168
9169 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009170 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9171 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009172 InsertNewInstBefore(NewSI, SI);
9173
9174 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9175 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009176 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009177 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009178 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009179 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009180 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009181 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009182}
9183
Evan Chengde621922009-03-31 20:42:45 +00009184static bool isSelect01(Constant *C1, Constant *C2) {
9185 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9186 if (!C1I)
9187 return false;
9188 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9189 if (!C2I)
9190 return false;
9191 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9192}
9193
9194/// FoldSelectIntoOp - Try fold the select into one of the operands to
9195/// facilitate further optimization.
9196Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9197 Value *FalseVal) {
9198 // See the comment above GetSelectFoldableOperands for a description of the
9199 // transformation we are doing here.
9200 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9201 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9202 !isa<Constant>(FalseVal)) {
9203 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9204 unsigned OpToFold = 0;
9205 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9206 OpToFold = 1;
9207 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9208 OpToFold = 2;
9209 }
9210
9211 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009212 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009213 Value *OOp = TVI->getOperand(2-OpToFold);
9214 // Avoid creating select between 2 constants unless it's selecting
9215 // between 0 and 1.
9216 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9217 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9218 InsertNewInstBefore(NewSel, SI);
9219 NewSel->takeName(TVI);
9220 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9221 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009222 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009223 }
9224 }
9225 }
9226 }
9227 }
9228
9229 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9230 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9231 !isa<Constant>(TrueVal)) {
9232 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9233 unsigned OpToFold = 0;
9234 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9235 OpToFold = 1;
9236 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9237 OpToFold = 2;
9238 }
9239
9240 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009241 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009242 Value *OOp = FVI->getOperand(2-OpToFold);
9243 // Avoid creating select between 2 constants unless it's selecting
9244 // between 0 and 1.
9245 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9246 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9247 InsertNewInstBefore(NewSel, SI);
9248 NewSel->takeName(FVI);
9249 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9250 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009251 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009252 }
9253 }
9254 }
9255 }
9256 }
9257
9258 return 0;
9259}
9260
Dan Gohman81b28ce2008-09-16 18:46:06 +00009261/// visitSelectInstWithICmp - Visit a SelectInst that has an
9262/// ICmpInst as its first operand.
9263///
9264Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9265 ICmpInst *ICI) {
9266 bool Changed = false;
9267 ICmpInst::Predicate Pred = ICI->getPredicate();
9268 Value *CmpLHS = ICI->getOperand(0);
9269 Value *CmpRHS = ICI->getOperand(1);
9270 Value *TrueVal = SI.getTrueValue();
9271 Value *FalseVal = SI.getFalseValue();
9272
9273 // Check cases where the comparison is with a constant that
9274 // can be adjusted to fit the min/max idiom. We may edit ICI in
9275 // place here, so make sure the select is the only user.
9276 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009277 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009278 switch (Pred) {
9279 default: break;
9280 case ICmpInst::ICMP_ULT:
9281 case ICmpInst::ICMP_SLT: {
9282 // X < MIN ? T : F --> F
9283 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9284 return ReplaceInstUsesWith(SI, FalseVal);
9285 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009286 Constant *AdjustedRHS = SubOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009287 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9288 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9289 Pred = ICmpInst::getSwappedPredicate(Pred);
9290 CmpRHS = AdjustedRHS;
9291 std::swap(FalseVal, TrueVal);
9292 ICI->setPredicate(Pred);
9293 ICI->setOperand(1, CmpRHS);
9294 SI.setOperand(1, TrueVal);
9295 SI.setOperand(2, FalseVal);
9296 Changed = true;
9297 }
9298 break;
9299 }
9300 case ICmpInst::ICMP_UGT:
9301 case ICmpInst::ICMP_SGT: {
9302 // X > MAX ? T : F --> F
9303 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9304 return ReplaceInstUsesWith(SI, FalseVal);
9305 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009306 Constant *AdjustedRHS = AddOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009307 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9308 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9309 Pred = ICmpInst::getSwappedPredicate(Pred);
9310 CmpRHS = AdjustedRHS;
9311 std::swap(FalseVal, TrueVal);
9312 ICI->setPredicate(Pred);
9313 ICI->setOperand(1, CmpRHS);
9314 SI.setOperand(1, TrueVal);
9315 SI.setOperand(2, FalseVal);
9316 Changed = true;
9317 }
9318 break;
9319 }
9320 }
9321
Dan Gohman1975d032008-10-30 20:40:10 +00009322 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9323 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009324 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009325 if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9326 match(FalseVal, m_ConstantInt<0>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009327 Pred = ICI->getPredicate();
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009328 else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9329 match(FalseVal, m_ConstantInt<-1>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009330 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9331
Dan Gohman1975d032008-10-30 20:40:10 +00009332 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9333 // If we are just checking for a icmp eq of a single bit and zext'ing it
9334 // to an integer, then shift the bit to the appropriate place and then
9335 // cast to integer to avoid the comparison.
9336 const APInt &Op1CV = CI->getValue();
9337
9338 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9339 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9340 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009341 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009342 Value *In = ICI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00009343 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009344 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009345 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9346 In->getName()+".lobit"),
9347 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009348 if (In->getType() != SI.getType())
9349 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009350 true/*SExt*/, "tmp", ICI);
9351
9352 if (Pred == ICmpInst::ICMP_SGT)
Owen Anderson73c6b712009-07-13 20:58:05 +00009353 In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
Dan Gohman1975d032008-10-30 20:40:10 +00009354 In->getName()+".not"), *ICI);
9355
9356 return ReplaceInstUsesWith(SI, In);
9357 }
9358 }
9359 }
9360
Dan Gohman81b28ce2008-09-16 18:46:06 +00009361 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9362 // Transform (X == Y) ? X : Y -> Y
9363 if (Pred == ICmpInst::ICMP_EQ)
9364 return ReplaceInstUsesWith(SI, FalseVal);
9365 // Transform (X != Y) ? X : Y -> X
9366 if (Pred == ICmpInst::ICMP_NE)
9367 return ReplaceInstUsesWith(SI, TrueVal);
9368 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9369
9370 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9371 // Transform (X == Y) ? Y : X -> X
9372 if (Pred == ICmpInst::ICMP_EQ)
9373 return ReplaceInstUsesWith(SI, FalseVal);
9374 // Transform (X != Y) ? Y : X -> Y
9375 if (Pred == ICmpInst::ICMP_NE)
9376 return ReplaceInstUsesWith(SI, TrueVal);
9377 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9378 }
9379
9380 /// NOTE: if we wanted to, this is where to detect integer ABS
9381
9382 return Changed ? &SI : 0;
9383}
9384
Chris Lattner3d69f462004-03-12 05:52:32 +00009385Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009386 Value *CondVal = SI.getCondition();
9387 Value *TrueVal = SI.getTrueValue();
9388 Value *FalseVal = SI.getFalseValue();
9389
9390 // select true, X, Y -> X
9391 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009392 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009393 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009394
9395 // select C, X, X -> X
9396 if (TrueVal == FalseVal)
9397 return ReplaceInstUsesWith(SI, TrueVal);
9398
Chris Lattnere87597f2004-10-16 18:11:37 +00009399 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9400 return ReplaceInstUsesWith(SI, FalseVal);
9401 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9402 return ReplaceInstUsesWith(SI, TrueVal);
9403 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9404 if (isa<Constant>(TrueVal))
9405 return ReplaceInstUsesWith(SI, TrueVal);
9406 else
9407 return ReplaceInstUsesWith(SI, FalseVal);
9408 }
9409
Reid Spencer4fe16d62007-01-11 18:21:29 +00009410 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009411 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009412 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009413 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009414 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009415 } else {
9416 // Change: A = select B, false, C --> A = and !B, C
9417 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009418 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009419 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009420 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009421 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009422 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009423 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009424 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009425 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009426 } else {
9427 // Change: A = select B, C, true --> A = or !B, C
9428 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009429 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009430 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009431 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009432 }
9433 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009434
9435 // select a, b, a -> a&b
9436 // select a, a, b -> a|b
9437 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009438 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009439 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009440 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009441 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009442
Chris Lattner2eefe512004-04-09 19:05:30 +00009443 // Selecting between two integer constants?
9444 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9445 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009446 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009447 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009448 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009449 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009450 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009451 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009452 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009453 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009454 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009455 }
Chris Lattner457dd822004-06-09 07:59:58 +00009456
Reid Spencere4d87aa2006-12-23 06:05:41 +00009457 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009458 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009459 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009460 // non-constant value, eliminate this whole mess. This corresponds to
9461 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009462 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009463 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009464 cast<Constant>(IC->getOperand(1))->isNullValue())
9465 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9466 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009467 isa<ConstantInt>(ICA->getOperand(1)) &&
9468 (ICA->getOperand(1) == TrueValC ||
9469 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009470 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9471 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009472 // know whether we have a icmp_ne or icmp_eq and whether the
9473 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009474 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009475 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009476 Value *V = ICA;
9477 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009478 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009479 Instruction::Xor, V, ICA->getOperand(1)), SI);
9480 return ReplaceInstUsesWith(SI, V);
9481 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009482 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009483 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009484
9485 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009486 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9487 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009488 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009489 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9490 // This is not safe in general for floating point:
9491 // consider X== -0, Y== +0.
9492 // It becomes safe if either operand is a nonzero constant.
9493 ConstantFP *CFPt, *CFPf;
9494 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9495 !CFPt->getValueAPF().isZero()) ||
9496 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9497 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009498 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009499 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009500 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009501 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009502 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009503 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009504
Reid Spencere4d87aa2006-12-23 06:05:41 +00009505 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009506 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009507 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9508 // This is not safe in general for floating point:
9509 // consider X== -0, Y== +0.
9510 // It becomes safe if either operand is a nonzero constant.
9511 ConstantFP *CFPt, *CFPf;
9512 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9513 !CFPt->getValueAPF().isZero()) ||
9514 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9515 !CFPf->getValueAPF().isZero()))
9516 return ReplaceInstUsesWith(SI, FalseVal);
9517 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009518 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009519 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9520 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009521 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009522 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009523 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009524 }
9525
9526 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009527 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9528 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9529 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009530
Chris Lattner87875da2005-01-13 22:52:24 +00009531 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9532 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9533 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009534 Instruction *AddOp = 0, *SubOp = 0;
9535
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009536 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9537 if (TI->getOpcode() == FI->getOpcode())
9538 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9539 return IV;
9540
9541 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9542 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009543 if ((TI->getOpcode() == Instruction::Sub &&
9544 FI->getOpcode() == Instruction::Add) ||
9545 (TI->getOpcode() == Instruction::FSub &&
9546 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009547 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009548 } else if ((FI->getOpcode() == Instruction::Sub &&
9549 TI->getOpcode() == Instruction::Add) ||
9550 (FI->getOpcode() == Instruction::FSub &&
9551 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009552 AddOp = TI; SubOp = FI;
9553 }
9554
9555 if (AddOp) {
9556 Value *OtherAddOp = 0;
9557 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9558 OtherAddOp = AddOp->getOperand(1);
9559 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9560 OtherAddOp = AddOp->getOperand(0);
9561 }
9562
9563 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009564 // So at this point we know we have (Y -> OtherAddOp):
9565 // select C, (add X, Y), (sub X, Z)
9566 Value *NegVal; // Compute -Z
9567 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009568 NegVal = Context->getConstantExprNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009569 } else {
9570 NegVal = InsertNewInstBefore(
Owen Anderson0a5372e2009-07-13 04:09:18 +00009571 BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9572 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009573 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009574
9575 Value *NewTrueOp = OtherAddOp;
9576 Value *NewFalseOp = NegVal;
9577 if (AddOp != TI)
9578 std::swap(NewTrueOp, NewFalseOp);
9579 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009580 SelectInst::Create(CondVal, NewTrueOp,
9581 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009582
9583 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009584 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009585 }
9586 }
9587 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009588
Chris Lattnere576b912004-04-09 23:46:01 +00009589 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009590 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009591 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9592 if (FoldI)
9593 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009594 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009595
9596 if (BinaryOperator::isNot(CondVal)) {
9597 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9598 SI.setOperand(1, FalseVal);
9599 SI.setOperand(2, TrueVal);
9600 return &SI;
9601 }
9602
Chris Lattner3d69f462004-03-12 05:52:32 +00009603 return 0;
9604}
9605
Dan Gohmaneee962e2008-04-10 18:43:06 +00009606/// EnforceKnownAlignment - If the specified pointer points to an object that
9607/// we control, modify the object's alignment to PrefAlign. This isn't
9608/// often possible though. If alignment is important, a more reliable approach
9609/// is to simply align all global variables and allocation instructions to
9610/// their preferred alignment from the beginning.
9611///
9612static unsigned EnforceKnownAlignment(Value *V,
9613 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009614
Dan Gohmaneee962e2008-04-10 18:43:06 +00009615 User *U = dyn_cast<User>(V);
9616 if (!U) return Align;
9617
Dan Gohmanca178902009-07-17 20:47:02 +00009618 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009619 default: break;
9620 case Instruction::BitCast:
9621 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9622 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009623 // If all indexes are zero, it is just the alignment of the base pointer.
9624 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009625 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009626 if (!isa<Constant>(*i) ||
9627 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009628 AllZeroOperands = false;
9629 break;
9630 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009631
9632 if (AllZeroOperands) {
9633 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009634 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009635 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009636 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009637 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009638 }
9639
9640 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9641 // If there is a large requested alignment and we can, bump up the alignment
9642 // of the global.
9643 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009644 if (GV->getAlignment() >= PrefAlign)
9645 Align = GV->getAlignment();
9646 else {
9647 GV->setAlignment(PrefAlign);
9648 Align = PrefAlign;
9649 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009650 }
9651 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9652 // If there is a requested alignment and if this is an alloca, round up. We
9653 // don't do this for malloc, because some systems can't respect the request.
9654 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009655 if (AI->getAlignment() >= PrefAlign)
9656 Align = AI->getAlignment();
9657 else {
9658 AI->setAlignment(PrefAlign);
9659 Align = PrefAlign;
9660 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009661 }
9662 }
9663
9664 return Align;
9665}
9666
9667/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9668/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9669/// and it is more than the alignment of the ultimate object, see if we can
9670/// increase the alignment of the ultimate object, making this check succeed.
9671unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9672 unsigned PrefAlign) {
9673 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9674 sizeof(PrefAlign) * CHAR_BIT;
9675 APInt Mask = APInt::getAllOnesValue(BitWidth);
9676 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9677 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9678 unsigned TrailZ = KnownZero.countTrailingOnes();
9679 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9680
9681 if (PrefAlign > Align)
9682 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9683
9684 // We don't need to make any adjustment.
9685 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009686}
9687
Chris Lattnerf497b022008-01-13 23:50:23 +00009688Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009689 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009690 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009691 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009692 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009693
9694 if (CopyAlign < MinAlign) {
Owen Andersona547b472009-07-09 18:36:20 +00009695 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9696 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009697 return MI;
9698 }
9699
9700 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9701 // load/store.
9702 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9703 if (MemOpLength == 0) return 0;
9704
Chris Lattner37ac6082008-01-14 00:28:35 +00009705 // Source and destination pointer types are always "i8*" for intrinsic. See
9706 // if the size is something we can handle with a single primitive load/store.
9707 // A single load+store correctly handles overlapping memory in the memmove
9708 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009709 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009710 if (Size == 0) return MI; // Delete this mem transfer.
9711
9712 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009713 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009714
Chris Lattner37ac6082008-01-14 00:28:35 +00009715 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009716 Type *NewPtrTy =
9717 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009718
9719 // Memcpy forces the use of i8* for the source and destination. That means
9720 // that if you're using memcpy to move one double around, you'll get a cast
9721 // from double* to i8*. We'd much rather use a double load+store rather than
9722 // an i64 load+store, here because this improves the odds that the source or
9723 // dest address will be promotable. See if we can find a better type than the
9724 // integer datatype.
9725 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9726 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9727 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9728 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9729 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009730 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009731 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9732 if (STy->getNumElements() == 1)
9733 SrcETy = STy->getElementType(0);
9734 else
9735 break;
9736 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9737 if (ATy->getNumElements() == 1)
9738 SrcETy = ATy->getElementType();
9739 else
9740 break;
9741 } else
9742 break;
9743 }
9744
Dan Gohman8f8e2692008-05-23 01:52:21 +00009745 if (SrcETy->isSingleValueType())
Owen Andersond672ecb2009-07-03 00:17:18 +00009746 NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009747 }
9748 }
9749
9750
Chris Lattnerf497b022008-01-13 23:50:23 +00009751 // If the memcpy/memmove provides better alignment info than we can
9752 // infer, use it.
9753 SrcAlign = std::max(SrcAlign, CopyAlign);
9754 DstAlign = std::max(DstAlign, CopyAlign);
9755
9756 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9757 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009758 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9759 InsertNewInstBefore(L, *MI);
9760 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9761
9762 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009763 MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009764 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009765}
Chris Lattner3d69f462004-03-12 05:52:32 +00009766
Chris Lattner69ea9d22008-04-30 06:39:11 +00009767Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9768 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009769 if (MI->getAlignment() < Alignment) {
Owen Andersona547b472009-07-09 18:36:20 +00009770 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9771 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009772 return MI;
9773 }
9774
9775 // Extract the length and alignment and fill if they are constant.
9776 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9777 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9778 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9779 return 0;
9780 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009781 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009782
9783 // If the length is zero, this is a no-op
9784 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9785
9786 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9787 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009788 const Type *ITy = Context->getIntegerType(Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009789
9790 Value *Dest = MI->getDest();
Owen Andersond672ecb2009-07-03 00:17:18 +00009791 Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009792
9793 // Alignment 0 is identity for alignment 1 for memset, but not store.
9794 if (Alignment == 0) Alignment = 1;
9795
9796 // Extract the fill value and store.
9797 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersond672ecb2009-07-03 00:17:18 +00009798 InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9799 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009800
9801 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009802 MI->setLength(Context->getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009803 return MI;
9804 }
9805
9806 return 0;
9807}
9808
9809
Chris Lattner8b0ea312006-01-13 20:11:04 +00009810/// visitCallInst - CallInst simplification. This mostly only handles folding
9811/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9812/// the heavy lifting.
9813///
Chris Lattner9fe38862003-06-19 17:00:31 +00009814Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009815 // If the caller function is nounwind, mark the call as nounwind, even if the
9816 // callee isn't.
9817 if (CI.getParent()->getParent()->doesNotThrow() &&
9818 !CI.doesNotThrow()) {
9819 CI.setDoesNotThrow();
9820 return &CI;
9821 }
9822
9823
9824
Chris Lattner8b0ea312006-01-13 20:11:04 +00009825 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9826 if (!II) return visitCallSite(&CI);
9827
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009828 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9829 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009830 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009831 bool Changed = false;
9832
9833 // memmove/cpy/set of zero bytes is a noop.
9834 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9835 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9836
Chris Lattner35b9e482004-10-12 04:52:52 +00009837 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009838 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009839 // Replace the instruction with just byte operations. We would
9840 // transform other cases to loads/stores, but we don't know if
9841 // alignment is sufficient.
9842 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009843 }
9844
Chris Lattner35b9e482004-10-12 04:52:52 +00009845 // If we have a memmove and the source operation is a constant global,
9846 // then the source and dest pointers can't alias, so we can change this
9847 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009848 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009849 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9850 if (GVSrc->isConstant()) {
9851 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009852 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9853 const Type *Tys[1];
9854 Tys[0] = CI.getOperand(3)->getType();
9855 CI.setOperand(0,
9856 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009857 Changed = true;
9858 }
Chris Lattnera935db82008-05-28 05:30:41 +00009859
9860 // memmove(x,x,size) -> noop.
9861 if (MMI->getSource() == MMI->getDest())
9862 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009863 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009864
Chris Lattner95a959d2006-03-06 20:18:44 +00009865 // If we can determine a pointer alignment that is bigger than currently
9866 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009867 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009868 if (Instruction *I = SimplifyMemTransfer(MI))
9869 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009870 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9871 if (Instruction *I = SimplifyMemSet(MSI))
9872 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009873 }
9874
Chris Lattner8b0ea312006-01-13 20:11:04 +00009875 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009876 }
9877
9878 switch (II->getIntrinsicID()) {
9879 default: break;
9880 case Intrinsic::bswap:
9881 // bswap(bswap(x)) -> x
9882 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9883 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9884 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9885 break;
9886 case Intrinsic::ppc_altivec_lvx:
9887 case Intrinsic::ppc_altivec_lvxl:
9888 case Intrinsic::x86_sse_loadu_ps:
9889 case Intrinsic::x86_sse2_loadu_pd:
9890 case Intrinsic::x86_sse2_loadu_dq:
9891 // Turn PPC lvx -> load if the pointer is known aligned.
9892 // Turn X86 loadups -> load if the pointer is known aligned.
9893 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9894 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00009895 Context->getPointerTypeUnqual(II->getType()),
Chris Lattner0521e3c2008-06-18 04:33:20 +00009896 CI);
9897 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009898 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009899 break;
9900 case Intrinsic::ppc_altivec_stvx:
9901 case Intrinsic::ppc_altivec_stvxl:
9902 // Turn stvx -> store if the pointer is known aligned.
9903 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9904 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009905 Context->getPointerTypeUnqual(II->getOperand(1)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009906 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9907 return new StoreInst(II->getOperand(1), Ptr);
9908 }
9909 break;
9910 case Intrinsic::x86_sse_storeu_ps:
9911 case Intrinsic::x86_sse2_storeu_pd:
9912 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009913 // Turn X86 storeu -> store if the pointer is known aligned.
9914 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9915 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009916 Context->getPointerTypeUnqual(II->getOperand(2)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009917 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9918 return new StoreInst(II->getOperand(2), Ptr);
9919 }
9920 break;
9921
9922 case Intrinsic::x86_sse_cvttss2si: {
9923 // These intrinsics only demands the 0th element of its input vector. If
9924 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009925 unsigned VWidth =
9926 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9927 APInt DemandedElts(VWidth, 1);
9928 APInt UndefElts(VWidth, 0);
9929 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009930 UndefElts)) {
9931 II->setOperand(1, V);
9932 return II;
9933 }
9934 break;
9935 }
9936
9937 case Intrinsic::ppc_altivec_vperm:
9938 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9939 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9940 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009941
Chris Lattner0521e3c2008-06-18 04:33:20 +00009942 // Check that all of the elements are integer constants or undefs.
9943 bool AllEltsOk = true;
9944 for (unsigned i = 0; i != 16; ++i) {
9945 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9946 !isa<UndefValue>(Mask->getOperand(i))) {
9947 AllEltsOk = false;
9948 break;
9949 }
9950 }
9951
9952 if (AllEltsOk) {
9953 // Cast the input vectors to byte vectors.
9954 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9955 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00009956 Value *Result = Context->getUndef(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009957
Chris Lattner0521e3c2008-06-18 04:33:20 +00009958 // Only extract each element once.
9959 Value *ExtractedElts[32];
9960 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9961
Chris Lattnere2ed0572006-04-06 19:19:17 +00009962 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009963 if (isa<UndefValue>(Mask->getOperand(i)))
9964 continue;
9965 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9966 Idx &= 31; // Match the hardware behavior.
9967
9968 if (ExtractedElts[Idx] == 0) {
9969 Instruction *Elt =
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009970 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
9971 Context->getConstantInt(Type::Int32Ty, Idx&15, false), "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009972 InsertNewInstBefore(Elt, CI);
9973 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009974 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009975
Chris Lattner0521e3c2008-06-18 04:33:20 +00009976 // Insert this value into the result vector.
9977 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009978 Context->getConstantInt(Type::Int32Ty, i, false),
9979 "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009980 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009981 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009982 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009983 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009984 }
9985 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009986
Chris Lattner0521e3c2008-06-18 04:33:20 +00009987 case Intrinsic::stackrestore: {
9988 // If the save is right next to the restore, remove the restore. This can
9989 // happen when variable allocas are DCE'd.
9990 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9991 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9992 BasicBlock::iterator BI = SS;
9993 if (&*++BI == II)
9994 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009995 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009996 }
9997
9998 // Scan down this block to see if there is another stack restore in the
9999 // same block without an intervening call/alloca.
10000 BasicBlock::iterator BI = II;
10001 TerminatorInst *TI = II->getParent()->getTerminator();
10002 bool CannotRemove = false;
10003 for (++BI; &*BI != TI; ++BI) {
10004 if (isa<AllocaInst>(BI)) {
10005 CannotRemove = true;
10006 break;
10007 }
Chris Lattneraa0bf522008-06-25 05:59:28 +000010008 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10009 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10010 // If there is a stackrestore below this one, remove this one.
10011 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10012 return EraseInstFromFunction(CI);
10013 // Otherwise, ignore the intrinsic.
10014 } else {
10015 // If we found a non-intrinsic call, we can't remove the stack
10016 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010017 CannotRemove = true;
10018 break;
10019 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010020 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010021 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010022
10023 // If the stack restore is in a return/unwind block and if there are no
10024 // allocas or calls between the restore and the return, nuke the restore.
10025 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10026 return EraseInstFromFunction(CI);
10027 break;
10028 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010029 }
10030
Chris Lattner8b0ea312006-01-13 20:11:04 +000010031 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010032}
10033
10034// InvokeInst simplification
10035//
10036Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010037 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010038}
10039
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010040/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10041/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010042static bool isSafeToEliminateVarargsCast(const CallSite CS,
10043 const CastInst * const CI,
10044 const TargetData * const TD,
10045 const int ix) {
10046 if (!CI->isLosslessCast())
10047 return false;
10048
10049 // The size of ByVal arguments is derived from the type, so we
10050 // can't change to a type with a different size. If the size were
10051 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010052 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010053 return true;
10054
10055 const Type* SrcTy =
10056 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10057 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10058 if (!SrcTy->isSized() || !DstTy->isSized())
10059 return false;
Duncan Sands777d2302009-05-09 07:06:46 +000010060 if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010061 return false;
10062 return true;
10063}
10064
Chris Lattnera44d8a22003-10-07 22:32:43 +000010065// visitCallSite - Improvements for call and invoke instructions.
10066//
10067Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010068 bool Changed = false;
10069
10070 // If the callee is a constexpr cast of a function, attempt to move the cast
10071 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010072 if (transformConstExprCastCall(CS)) return 0;
10073
Chris Lattner6c266db2003-10-07 22:54:13 +000010074 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010075
Chris Lattner08b22ec2005-05-13 07:09:09 +000010076 if (Function *CalleeF = dyn_cast<Function>(Callee))
10077 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10078 Instruction *OldCall = CS.getInstruction();
10079 // If the call and callee calling conventions don't match, this call must
10080 // be unreachable, as the call is undefined.
Owen Andersond672ecb2009-07-03 00:17:18 +000010081 new StoreInst(Context->getConstantIntTrue(),
10082 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10083 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +000010084 if (!OldCall->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000010085 OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010086 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10087 return EraseInstFromFunction(*OldCall);
10088 return 0;
10089 }
10090
Chris Lattner17be6352004-10-18 02:59:09 +000010091 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10092 // This instruction is not reachable, just remove it. We insert a store to
10093 // undef so that we know that this code is not reachable, despite the fact
10094 // that we can't modify the CFG here.
Owen Andersond672ecb2009-07-03 00:17:18 +000010095 new StoreInst(Context->getConstantIntTrue(),
10096 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +000010097 CS.getInstruction());
10098
10099 if (!CS.getInstruction()->use_empty())
10100 CS.getInstruction()->
Owen Andersond672ecb2009-07-03 00:17:18 +000010101 replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010102
10103 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10104 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010105 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Andersond672ecb2009-07-03 00:17:18 +000010106 Context->getConstantIntTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010107 }
Chris Lattner17be6352004-10-18 02:59:09 +000010108 return EraseInstFromFunction(*CS.getInstruction());
10109 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010110
Duncan Sandscdb6d922007-09-17 10:26:40 +000010111 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10112 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10113 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10114 return transformCallThroughTrampoline(CS);
10115
Chris Lattner6c266db2003-10-07 22:54:13 +000010116 const PointerType *PTy = cast<PointerType>(Callee->getType());
10117 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10118 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010119 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010120 // See if we can optimize any arguments passed through the varargs area of
10121 // the call.
10122 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010123 E = CS.arg_end(); I != E; ++I, ++ix) {
10124 CastInst *CI = dyn_cast<CastInst>(*I);
10125 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10126 *I = CI->getOperand(0);
10127 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010128 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010129 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010130 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010131
Duncan Sandsf0c33542007-12-19 21:13:37 +000010132 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010133 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010134 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010135 Changed = true;
10136 }
10137
Chris Lattner6c266db2003-10-07 22:54:13 +000010138 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010139}
10140
Chris Lattner9fe38862003-06-19 17:00:31 +000010141// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10142// attempt to move the cast to the arguments of the call/invoke.
10143//
10144bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10145 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10146 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010147 if (CE->getOpcode() != Instruction::BitCast ||
10148 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010149 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010150 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010151 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010152 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010153
10154 // Okay, this is a cast from a function to a different type. Unless doing so
10155 // would cause a type conversion of one of our arguments, change this call to
10156 // be a direct call with arguments casted to the appropriate types.
10157 //
10158 const FunctionType *FT = Callee->getFunctionType();
10159 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010160 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010161
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010162 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010163 return false; // TODO: Handle multiple return values.
10164
Chris Lattnerf78616b2004-01-14 06:06:08 +000010165 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010166 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010167 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010168 // Conversion is ok if changing from one pointer type to another or from
10169 // a pointer to an integer of the same size.
10170 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +000010171 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +000010172 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010173
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010174 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010175 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010176 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010177 return false; // Cannot transform this return value.
10178
Chris Lattner58d74912008-03-12 17:45:29 +000010179 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010180 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010181 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010182 return false; // Attribute not compatible with transformed value.
10183 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010184
Chris Lattnerf78616b2004-01-14 06:06:08 +000010185 // If the callsite is an invoke instruction, and the return value is used by
10186 // a PHI node in a successor, we cannot change the return type of the call
10187 // because there is no place to put the cast instruction (without breaking
10188 // the critical edge). Bail out in this case.
10189 if (!Caller->use_empty())
10190 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10191 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10192 UI != E; ++UI)
10193 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10194 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010195 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010196 return false;
10197 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010198
10199 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10200 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010201
Chris Lattner9fe38862003-06-19 17:00:31 +000010202 CallSite::arg_iterator AI = CS.arg_begin();
10203 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10204 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010205 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010206
10207 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010208 return false; // Cannot transform this parameter value.
10209
Devang Patel19c87462008-09-26 22:53:05 +000010210 if (CallerPAL.getParamAttributes(i + 1)
10211 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010212 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010213
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010214 // Converting from one pointer type to another or between a pointer and an
10215 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010216 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010217 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10218 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010219 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010220 }
10221
10222 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010223 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010224 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010225
Chris Lattner58d74912008-03-12 17:45:29 +000010226 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10227 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010228 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010229 // won't be dropping them. Check that these extra arguments have attributes
10230 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010231 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10232 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010233 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010234 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010235 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010236 return false;
10237 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010238
Chris Lattner9fe38862003-06-19 17:00:31 +000010239 // Okay, we decided that this is a safe thing to do: go ahead and start
10240 // inserting cast instructions as necessary...
10241 std::vector<Value*> Args;
10242 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010243 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010244 attrVec.reserve(NumCommonArgs);
10245
10246 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010247 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010248
10249 // If the return value is not being used, the type may not be compatible
10250 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010251 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010252
10253 // Add the new return attributes.
10254 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010255 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010256
10257 AI = CS.arg_begin();
10258 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10259 const Type *ParamTy = FT->getParamType(i);
10260 if ((*AI)->getType() == ParamTy) {
10261 Args.push_back(*AI);
10262 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010263 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010264 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010265 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010266 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010267 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010268
10269 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010270 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010271 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010272 }
10273
10274 // If the function takes more arguments than the call was taking, add them
10275 // now...
10276 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000010277 Args.push_back(Context->getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010278
10279 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010280 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010281 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +000010282 cerr << "WARNING: While resolving call to function '"
10283 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010284 } else {
10285 // Add all of the arguments in their promoted form to the arg list...
10286 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10287 const Type *PTy = getPromotedType((*AI)->getType());
10288 if (PTy != (*AI)->getType()) {
10289 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010290 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10291 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010292 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010293 InsertNewInstBefore(Cast, *Caller);
10294 Args.push_back(Cast);
10295 } else {
10296 Args.push_back(*AI);
10297 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010298
Duncan Sandse1e520f2008-01-13 08:02:44 +000010299 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010300 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010301 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010302 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010303 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010304 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010305
Devang Patel19c87462008-09-26 22:53:05 +000010306 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10307 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10308
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010309 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +000010310 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010311
Devang Patel05988662008-09-25 21:00:45 +000010312 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010313
Chris Lattner9fe38862003-06-19 17:00:31 +000010314 Instruction *NC;
10315 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010316 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010317 Args.begin(), Args.end(),
10318 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010319 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010320 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010321 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010322 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10323 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010324 CallInst *CI = cast<CallInst>(Caller);
10325 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010326 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010327 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010328 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010329 }
10330
Chris Lattner6934a042007-02-11 01:23:03 +000010331 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010332 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010333 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010334 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010335 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010336 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010337 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010338
10339 // If this is an invoke instruction, we should insert it after the first
10340 // non-phi, instruction in the normal successor block.
10341 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010342 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010343 InsertNewInstBefore(NC, *I);
10344 } else {
10345 // Otherwise, it's a call, just insert cast right after the call instr
10346 InsertNewInstBefore(NC, *Caller);
10347 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010348 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010349 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000010350 NV = Context->getUndef(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010351 }
10352 }
10353
10354 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10355 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010356 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010357 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010358 return true;
10359}
10360
Duncan Sandscdb6d922007-09-17 10:26:40 +000010361// transformCallThroughTrampoline - Turn a call to a function created by the
10362// init_trampoline intrinsic into a direct call to the underlying function.
10363//
10364Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10365 Value *Callee = CS.getCalledValue();
10366 const PointerType *PTy = cast<PointerType>(Callee->getType());
10367 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010368 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010369
10370 // If the call already has the 'nest' attribute somewhere then give up -
10371 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010372 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010373 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010374
10375 IntrinsicInst *Tramp =
10376 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10377
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010378 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010379 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10380 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10381
Devang Patel05988662008-09-25 21:00:45 +000010382 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010383 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010384 unsigned NestIdx = 1;
10385 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010386 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010387
10388 // Look for a parameter marked with the 'nest' attribute.
10389 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10390 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010391 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010392 // Record the parameter type and any other attributes.
10393 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010394 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010395 break;
10396 }
10397
10398 if (NestTy) {
10399 Instruction *Caller = CS.getInstruction();
10400 std::vector<Value*> NewArgs;
10401 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10402
Devang Patel05988662008-09-25 21:00:45 +000010403 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010404 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010405
Duncan Sandscdb6d922007-09-17 10:26:40 +000010406 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010407 // mean appending it. Likewise for attributes.
10408
Devang Patel19c87462008-09-26 22:53:05 +000010409 // Add any result attributes.
10410 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010411 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010412
Duncan Sandscdb6d922007-09-17 10:26:40 +000010413 {
10414 unsigned Idx = 1;
10415 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10416 do {
10417 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010418 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010419 Value *NestVal = Tramp->getOperand(3);
10420 if (NestVal->getType() != NestTy)
10421 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10422 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010423 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010424 }
10425
10426 if (I == E)
10427 break;
10428
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010429 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010430 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010431 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010432 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010433 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010434
10435 ++Idx, ++I;
10436 } while (1);
10437 }
10438
Devang Patel19c87462008-09-26 22:53:05 +000010439 // Add any function attributes.
10440 if (Attributes Attr = Attrs.getFnAttributes())
10441 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10442
Duncan Sandscdb6d922007-09-17 10:26:40 +000010443 // The trampoline may have been bitcast to a bogus type (FTy).
10444 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010445 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010446
Duncan Sandscdb6d922007-09-17 10:26:40 +000010447 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010448 NewTypes.reserve(FTy->getNumParams()+1);
10449
Duncan Sandscdb6d922007-09-17 10:26:40 +000010450 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010451 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010452 {
10453 unsigned Idx = 1;
10454 FunctionType::param_iterator I = FTy->param_begin(),
10455 E = FTy->param_end();
10456
10457 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010458 if (Idx == NestIdx)
10459 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010460 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010461
10462 if (I == E)
10463 break;
10464
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010465 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010466 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010467
10468 ++Idx, ++I;
10469 } while (1);
10470 }
10471
10472 // Replace the trampoline call with a direct call. Let the generic
10473 // code sort out any function type mismatches.
10474 FunctionType *NewFTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000010475 Context->getFunctionType(FTy->getReturnType(), NewTypes,
10476 FTy->isVarArg());
10477 Constant *NewCallee =
10478 NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10479 NestF : Context->getConstantExprBitCast(NestF,
10480 Context->getPointerTypeUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +000010481 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010482
10483 Instruction *NewCaller;
10484 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010485 NewCaller = InvokeInst::Create(NewCallee,
10486 II->getNormalDest(), II->getUnwindDest(),
10487 NewArgs.begin(), NewArgs.end(),
10488 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010489 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010490 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010491 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010492 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10493 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010494 if (cast<CallInst>(Caller)->isTailCall())
10495 cast<CallInst>(NewCaller)->setTailCall();
10496 cast<CallInst>(NewCaller)->
10497 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010498 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010499 }
10500 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10501 Caller->replaceAllUsesWith(NewCaller);
10502 Caller->eraseFromParent();
10503 RemoveFromWorkList(Caller);
10504 return 0;
10505 }
10506 }
10507
10508 // Replace the trampoline call with a direct call. Since there is no 'nest'
10509 // parameter, there is no need to adjust the argument list. Let the generic
10510 // code sort out any function type mismatches.
10511 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010512 NestF->getType() == PTy ? NestF :
10513 Context->getConstantExprBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010514 CS.setCalledFunction(NewCallee);
10515 return CS.getInstruction();
10516}
10517
Chris Lattner7da52b22006-11-01 04:51:18 +000010518/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10519/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10520/// and a single binop.
10521Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10522 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010523 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010524 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010525 Value *LHSVal = FirstInst->getOperand(0);
10526 Value *RHSVal = FirstInst->getOperand(1);
10527
10528 const Type *LHSType = LHSVal->getType();
10529 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010530
10531 // Scan to see if all operands are the same opcode, all have one use, and all
10532 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010533 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010534 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010535 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010536 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010537 // types or GEP's with different index types.
10538 I->getOperand(0)->getType() != LHSType ||
10539 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010540 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010541
10542 // If they are CmpInst instructions, check their predicates
10543 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10544 if (cast<CmpInst>(I)->getPredicate() !=
10545 cast<CmpInst>(FirstInst)->getPredicate())
10546 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010547
10548 // Keep track of which operand needs a phi node.
10549 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10550 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010551 }
10552
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010553 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010554
Chris Lattner7da52b22006-11-01 04:51:18 +000010555 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010556 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010557 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010558 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010559 NewLHS = PHINode::Create(LHSType,
10560 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010561 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10562 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010563 InsertNewInstBefore(NewLHS, PN);
10564 LHSVal = NewLHS;
10565 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010566
10567 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010568 NewRHS = PHINode::Create(RHSType,
10569 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010570 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10571 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010572 InsertNewInstBefore(NewRHS, PN);
10573 RHSVal = NewRHS;
10574 }
10575
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010576 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010577 if (NewLHS || NewRHS) {
10578 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10579 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10580 if (NewLHS) {
10581 Value *NewInLHS = InInst->getOperand(0);
10582 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10583 }
10584 if (NewRHS) {
10585 Value *NewInRHS = InInst->getOperand(1);
10586 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10587 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010588 }
10589 }
10590
Chris Lattner7da52b22006-11-01 04:51:18 +000010591 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010592 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010593 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Owen Anderson333c4002009-07-09 23:48:35 +000010594 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10595 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010596}
10597
Chris Lattner05f18922008-12-01 02:34:36 +000010598Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10599 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10600
10601 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10602 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010603 // This is true if all GEP bases are allocas and if all indices into them are
10604 // constants.
10605 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010606
10607 // Scan to see if all operands are the same opcode, all have one use, and all
10608 // kill their operands (i.e. the operands have one use).
10609 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10610 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10611 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10612 GEP->getNumOperands() != FirstInst->getNumOperands())
10613 return 0;
10614
Chris Lattner36d3e322009-02-21 00:46:50 +000010615 // Keep track of whether or not all GEPs are of alloca pointers.
10616 if (AllBasePointersAreAllocas &&
10617 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10618 !GEP->hasAllConstantIndices()))
10619 AllBasePointersAreAllocas = false;
10620
Chris Lattner05f18922008-12-01 02:34:36 +000010621 // Compare the operand lists.
10622 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10623 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10624 continue;
10625
10626 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10627 // if one of the PHIs has a constant for the index. The index may be
10628 // substantially cheaper to compute for the constants, so making it a
10629 // variable index could pessimize the path. This also handles the case
10630 // for struct indices, which must always be constant.
10631 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10632 isa<ConstantInt>(GEP->getOperand(op)))
10633 return 0;
10634
10635 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10636 return 0;
10637 FixedOperands[op] = 0; // Needs a PHI.
10638 }
10639 }
10640
Chris Lattner36d3e322009-02-21 00:46:50 +000010641 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010642 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010643 // offset calculation, but all the predecessors will have to materialize the
10644 // stack address into a register anyway. We'd actually rather *clone* the
10645 // load up into the predecessors so that we have a load of a gep of an alloca,
10646 // which can usually all be folded into the load.
10647 if (AllBasePointersAreAllocas)
10648 return 0;
10649
Chris Lattner05f18922008-12-01 02:34:36 +000010650 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10651 // that is variable.
10652 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10653
10654 bool HasAnyPHIs = false;
10655 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10656 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10657 Value *FirstOp = FirstInst->getOperand(i);
10658 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10659 FirstOp->getName()+".pn");
10660 InsertNewInstBefore(NewPN, PN);
10661
10662 NewPN->reserveOperandSpace(e);
10663 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10664 OperandPhis[i] = NewPN;
10665 FixedOperands[i] = NewPN;
10666 HasAnyPHIs = true;
10667 }
10668
10669
10670 // Add all operands to the new PHIs.
10671 if (HasAnyPHIs) {
10672 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10673 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10674 BasicBlock *InBB = PN.getIncomingBlock(i);
10675
10676 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10677 if (PHINode *OpPhi = OperandPhis[op])
10678 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10679 }
10680 }
10681
10682 Value *Base = FixedOperands[0];
10683 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10684 FixedOperands.end());
10685}
10686
10687
Chris Lattner21550882009-02-23 05:56:17 +000010688/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10689/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010690/// obvious the value of the load is not changed from the point of the load to
10691/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010692///
10693/// Finally, it is safe, but not profitable, to sink a load targetting a
10694/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10695/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010696static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010697 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10698
10699 for (++BBI; BBI != E; ++BBI)
10700 if (BBI->mayWriteToMemory())
10701 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010702
10703 // Check for non-address taken alloca. If not address-taken already, it isn't
10704 // profitable to do this xform.
10705 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10706 bool isAddressTaken = false;
10707 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10708 UI != E; ++UI) {
10709 if (isa<LoadInst>(UI)) continue;
10710 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10711 // If storing TO the alloca, then the address isn't taken.
10712 if (SI->getOperand(1) == AI) continue;
10713 }
10714 isAddressTaken = true;
10715 break;
10716 }
10717
Chris Lattner36d3e322009-02-21 00:46:50 +000010718 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010719 return false;
10720 }
10721
Chris Lattner36d3e322009-02-21 00:46:50 +000010722 // If this load is a load from a GEP with a constant offset from an alloca,
10723 // then we don't want to sink it. In its present form, it will be
10724 // load [constant stack offset]. Sinking it will cause us to have to
10725 // materialize the stack addresses in each predecessor in a register only to
10726 // do a shared load from register in the successor.
10727 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10728 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10729 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10730 return false;
10731
Chris Lattner76c73142006-11-01 07:13:54 +000010732 return true;
10733}
10734
Chris Lattner9fe38862003-06-19 17:00:31 +000010735
Chris Lattnerbac32862004-11-14 19:13:23 +000010736// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10737// operator and they all are only used by the PHI, PHI together their
10738// inputs, and do the operation once, to the result of the PHI.
10739Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10740 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10741
10742 // Scan the instruction, looking for input operations that can be folded away.
10743 // If all input operands to the phi are the same instruction (e.g. a cast from
10744 // the same type or "+42") we can pull the operation through the PHI, reducing
10745 // code size and simplifying code.
10746 Constant *ConstantOp = 0;
10747 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010748 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010749 if (isa<CastInst>(FirstInst)) {
10750 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010751 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010752 // Can fold binop, compare or shift here if the RHS is a constant,
10753 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010754 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010755 if (ConstantOp == 0)
10756 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010757 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10758 isVolatile = LI->isVolatile();
10759 // We can't sink the load if the loaded value could be modified between the
10760 // load and the PHI.
10761 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010762 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010763 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010764
10765 // If the PHI is of volatile loads and the load block has multiple
10766 // successors, sinking it would remove a load of the volatile value from
10767 // the path through the other successor.
10768 if (isVolatile &&
10769 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10770 return 0;
10771
Chris Lattner9c080502006-11-01 07:43:41 +000010772 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010773 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010774 } else {
10775 return 0; // Cannot fold this operation.
10776 }
10777
10778 // Check to see if all arguments are the same operation.
10779 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10780 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10781 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010782 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010783 return 0;
10784 if (CastSrcTy) {
10785 if (I->getOperand(0)->getType() != CastSrcTy)
10786 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010787 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010788 // We can't sink the load if the loaded value could be modified between
10789 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010790 if (LI->isVolatile() != isVolatile ||
10791 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010792 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010793 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010794
Chris Lattner71042962008-07-08 17:18:32 +000010795 // If the PHI is of volatile loads and the load block has multiple
10796 // successors, sinking it would remove a load of the volatile value from
10797 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010798 if (isVolatile &&
10799 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10800 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010801
Chris Lattnerbac32862004-11-14 19:13:23 +000010802 } else if (I->getOperand(1) != ConstantOp) {
10803 return 0;
10804 }
10805 }
10806
10807 // Okay, they are all the same operation. Create a new PHI node of the
10808 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010809 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10810 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010811 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010812
10813 Value *InVal = FirstInst->getOperand(0);
10814 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010815
10816 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010817 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10818 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10819 if (NewInVal != InVal)
10820 InVal = 0;
10821 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10822 }
10823
10824 Value *PhiVal;
10825 if (InVal) {
10826 // The new PHI unions all of the same values together. This is really
10827 // common, so we handle it intelligently here for compile-time speed.
10828 PhiVal = InVal;
10829 delete NewPN;
10830 } else {
10831 InsertNewInstBefore(NewPN, PN);
10832 PhiVal = NewPN;
10833 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010834
Chris Lattnerbac32862004-11-14 19:13:23 +000010835 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010836 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010837 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010838 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010839 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010840 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Owen Anderson333c4002009-07-09 23:48:35 +000010841 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010842 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010843 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10844
10845 // If this was a volatile load that we are merging, make sure to loop through
10846 // and mark all the input loads as non-volatile. If we don't do this, we will
10847 // insert a new volatile load and the old ones will not be deletable.
10848 if (isVolatile)
10849 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10850 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10851
10852 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010853}
Chris Lattnera1be5662002-05-02 17:06:02 +000010854
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010855/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10856/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010857static bool DeadPHICycle(PHINode *PN,
10858 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010859 if (PN->use_empty()) return true;
10860 if (!PN->hasOneUse()) return false;
10861
10862 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010863 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010864 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010865
10866 // Don't scan crazily complex things.
10867 if (PotentiallyDeadPHIs.size() == 16)
10868 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010869
10870 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10871 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010872
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010873 return false;
10874}
10875
Chris Lattnercf5008a2007-11-06 21:52:06 +000010876/// PHIsEqualValue - Return true if this phi node is always equal to
10877/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10878/// z = some value; x = phi (y, z); y = phi (x, z)
10879static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10880 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10881 // See if we already saw this PHI node.
10882 if (!ValueEqualPHIs.insert(PN))
10883 return true;
10884
10885 // Don't scan crazily complex things.
10886 if (ValueEqualPHIs.size() == 16)
10887 return false;
10888
10889 // Scan the operands to see if they are either phi nodes or are equal to
10890 // the value.
10891 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10892 Value *Op = PN->getIncomingValue(i);
10893 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10894 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10895 return false;
10896 } else if (Op != NonPhiInVal)
10897 return false;
10898 }
10899
10900 return true;
10901}
10902
10903
Chris Lattner473945d2002-05-06 18:06:38 +000010904// PHINode simplification
10905//
Chris Lattner7e708292002-06-25 16:13:24 +000010906Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010907 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010908 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010909
Owen Anderson7e057142006-07-10 22:03:18 +000010910 if (Value *V = PN.hasConstantValue())
10911 return ReplaceInstUsesWith(PN, V);
10912
Owen Anderson7e057142006-07-10 22:03:18 +000010913 // If all PHI operands are the same operation, pull them through the PHI,
10914 // reducing code size.
10915 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010916 isa<Instruction>(PN.getIncomingValue(1)) &&
10917 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10918 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10919 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10920 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010921 PN.getIncomingValue(0)->hasOneUse())
10922 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10923 return Result;
10924
10925 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10926 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10927 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010928 if (PN.hasOneUse()) {
10929 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10930 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010931 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010932 PotentiallyDeadPHIs.insert(&PN);
10933 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersond672ecb2009-07-03 00:17:18 +000010934 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010935 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010936
10937 // If this phi has a single use, and if that use just computes a value for
10938 // the next iteration of a loop, delete the phi. This occurs with unused
10939 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10940 // common case here is good because the only other things that catch this
10941 // are induction variable analysis (sometimes) and ADCE, which is only run
10942 // late.
10943 if (PHIUser->hasOneUse() &&
10944 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10945 PHIUser->use_back() == &PN) {
Owen Andersond672ecb2009-07-03 00:17:18 +000010946 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010947 }
10948 }
Owen Anderson7e057142006-07-10 22:03:18 +000010949
Chris Lattnercf5008a2007-11-06 21:52:06 +000010950 // We sometimes end up with phi cycles that non-obviously end up being the
10951 // same value, for example:
10952 // z = some value; x = phi (y, z); y = phi (x, z)
10953 // where the phi nodes don't necessarily need to be in the same block. Do a
10954 // quick check to see if the PHI node only contains a single non-phi value, if
10955 // so, scan to see if the phi cycle is actually equal to that value.
10956 {
10957 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10958 // Scan for the first non-phi operand.
10959 while (InValNo != NumOperandVals &&
10960 isa<PHINode>(PN.getIncomingValue(InValNo)))
10961 ++InValNo;
10962
10963 if (InValNo != NumOperandVals) {
10964 Value *NonPhiInVal = PN.getOperand(InValNo);
10965
10966 // Scan the rest of the operands to see if there are any conflicts, if so
10967 // there is no need to recursively scan other phis.
10968 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10969 Value *OpVal = PN.getIncomingValue(InValNo);
10970 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10971 break;
10972 }
10973
10974 // If we scanned over all operands, then we have one unique value plus
10975 // phi values. Scan PHI nodes to see if they all merge in each other or
10976 // the value.
10977 if (InValNo == NumOperandVals) {
10978 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10979 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10980 return ReplaceInstUsesWith(PN, NonPhiInVal);
10981 }
10982 }
10983 }
Chris Lattner60921c92003-12-19 05:58:40 +000010984 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010985}
10986
Reid Spencer17212df2006-12-12 09:18:51 +000010987static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10988 Instruction *InsertPoint,
10989 InstCombiner *IC) {
Dan Gohman6de29f82009-06-15 22:12:54 +000010990 unsigned PtrSize = DTy->getScalarSizeInBits();
10991 unsigned VTySize = V->getType()->getScalarSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010992 // We must cast correctly to the pointer type. Ensure that we
10993 // sign extend the integer value if it is smaller as this is
10994 // used for address computation.
10995 Instruction::CastOps opcode =
10996 (VTySize < PtrSize ? Instruction::SExt :
10997 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10998 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010999}
11000
Chris Lattnera1be5662002-05-02 17:06:02 +000011001
Chris Lattner7e708292002-06-25 16:13:24 +000011002Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000011003 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000011004 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000011005 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011006 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000011007 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011008
Chris Lattnere87597f2004-10-16 18:11:37 +000011009 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000011010 return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011011
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011012 bool HasZeroPointerIndex = false;
11013 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11014 HasZeroPointerIndex = C->isNullValue();
11015
11016 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011017 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011018
Chris Lattner28977af2004-04-05 01:30:19 +000011019 // Eliminate unneeded casts for indices.
11020 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011021
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011022 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011023 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11024 i != e; ++i, ++GTI) {
Sanjiv Gupta7787d4a2009-04-24 02:37:54 +000011025 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000011026 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011027 if (CI->getOpcode() == Instruction::ZExt ||
11028 CI->getOpcode() == Instruction::SExt) {
11029 const Type *SrcTy = CI->getOperand(0)->getType();
11030 // We can eliminate a cast from i32 to i64 iff the target
11031 // is a 32-bit pointer target.
Dan Gohman6de29f82009-06-15 22:12:54 +000011032 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011033 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000011034 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000011035 }
11036 }
11037 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011038 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000011039 // to what we need. If narrower, sign-extend it to what we need.
11040 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011041 // insert it. This explicit cast can make subsequent optimizations more
11042 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000011043 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011044 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000011045 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011046 *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000011047 MadeChange = true;
11048 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000011049 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11050 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011051 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011052 MadeChange = true;
11053 }
Dan Gohman4f833d42008-09-11 23:06:38 +000011054 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11055 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011056 *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
Dan Gohman4f833d42008-09-11 23:06:38 +000011057 MadeChange = true;
11058 } else {
11059 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11060 GEP);
11061 *i = Op;
11062 MadeChange = true;
11063 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011064 }
Chris Lattner28977af2004-04-05 01:30:19 +000011065 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011066 }
Chris Lattner28977af2004-04-05 01:30:19 +000011067 if (MadeChange) return &GEP;
11068
Chris Lattner90ac28c2002-08-02 19:29:35 +000011069 // Combine Indices - If the source pointer to this getelementptr instruction
11070 // is a getelementptr instruction, combine the indices of the two
11071 // getelementptr instructions into a single instruction.
11072 //
Chris Lattner72588fc2007-02-15 22:48:32 +000011073 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000011074 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000011075 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000011076
11077 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000011078 // Note that if our source is a gep chain itself that we wait for that
11079 // chain to be resolved before we perform this transformation. This
11080 // avoids us creating a TON of code in some cases.
11081 //
11082 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11083 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11084 return 0; // Wait until our source is folded to completion.
11085
Chris Lattner72588fc2007-02-15 22:48:32 +000011086 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011087
11088 // Find out whether the last index in the source GEP is a sequential idx.
11089 bool EndsWithSequential = false;
11090 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11091 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011092 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011093
Chris Lattner90ac28c2002-08-02 19:29:35 +000011094 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011095 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011096 // Replace: gep (gep %P, long B), long A, ...
11097 // With: T = long A+B; gep %P, T, ...
11098 //
Chris Lattner620ce142004-05-07 22:09:22 +000011099 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011100 if (SO1 == Context->getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011101 Sum = GO1;
Owen Andersond672ecb2009-07-03 00:17:18 +000011102 } else if (GO1 == Context->getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011103 Sum = SO1;
11104 } else {
11105 // If they aren't the same type, convert both to an integer of the
11106 // target's pointer size.
11107 if (SO1->getType() != GO1->getType()) {
11108 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011109 SO1 =
11110 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011111 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011112 GO1 =
11113 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011114 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000011115 unsigned PS = TD->getPointerSizeInBits();
11116 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011117 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011118 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011119
Duncan Sands514ab342007-11-01 20:53:16 +000011120 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011121 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011122 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011123 } else {
11124 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000011125 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11126 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011127 }
11128 }
11129 }
Chris Lattner620ce142004-05-07 22:09:22 +000011130 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Andersond672ecb2009-07-03 00:17:18 +000011131 Sum = Context->getConstantExprAdd(cast<Constant>(SO1),
11132 cast<Constant>(GO1));
Chris Lattner620ce142004-05-07 22:09:22 +000011133 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011134 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011135 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011136 }
Chris Lattner28977af2004-04-05 01:30:19 +000011137 }
Chris Lattner620ce142004-05-07 22:09:22 +000011138
11139 // Recycle the GEP we already have if possible.
11140 if (SrcGEPOperands.size() == 2) {
11141 GEP.setOperand(0, SrcGEPOperands[0]);
11142 GEP.setOperand(1, Sum);
11143 return &GEP;
11144 } else {
11145 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11146 SrcGEPOperands.end()-1);
11147 Indices.push_back(Sum);
11148 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11149 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011150 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011151 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000011152 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011153 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000011154 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11155 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011156 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11157 }
11158
11159 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000011160 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11161 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000011162
Chris Lattner620ce142004-05-07 22:09:22 +000011163 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000011164 // GEP of global variable. If all of the indices for this GEP are
11165 // constants, we can promote this to a constexpr instead of an instruction.
11166
11167 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000011168 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000011169 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11170 for (; I != E && isa<Constant>(*I); ++I)
11171 Indices.push_back(cast<Constant>(*I));
11172
11173 if (I == E) { // If they are all constants...
Owen Andersond672ecb2009-07-03 00:17:18 +000011174 Constant *CE = Context->getConstantExprGetElementPtr(GV,
Chris Lattner55eb1c42007-01-31 04:40:53 +000011175 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000011176
11177 // Replace all uses of the GEP with the new constexpr...
11178 return ReplaceInstUsesWith(GEP, CE);
11179 }
Reid Spencer3da59db2006-11-27 01:05:10 +000011180 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000011181 if (!isa<PointerType>(X->getType())) {
11182 // Not interesting. Source pointer must be a cast from pointer.
11183 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011184 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11185 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011186 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011187 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11188 // into : GEP i8* X, ...
11189 //
Chris Lattnereed48272005-09-13 00:40:14 +000011190 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011191 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11192 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011193 if (const ArrayType *CATy =
11194 dyn_cast<ArrayType>(CPTy->getElementType())) {
11195 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11196 if (CATy->getElementType() == XTy->getElementType()) {
11197 // -> GEP i8* X, ...
11198 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11199 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11200 GEP.getName());
11201 } else if (const ArrayType *XATy =
11202 dyn_cast<ArrayType>(XTy->getElementType())) {
11203 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011204 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011205 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011206 // At this point, we know that the cast source type is a pointer
11207 // to an array of the same type as the destination pointer
11208 // array. Because the array type is never stepped over (there
11209 // is a leading zero) we can fold the cast into this GEP.
11210 GEP.setOperand(0, X);
11211 return &GEP;
11212 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011213 }
11214 }
Chris Lattnereed48272005-09-13 00:40:14 +000011215 } else if (GEP.getNumOperands() == 2) {
11216 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011217 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11218 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011219 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11220 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11221 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011222 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11223 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011224 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011225 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011226 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000011227 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000011228 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011229 // V and GEP are both pointer types --> BitCast
11230 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011231 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011232
11233 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011234 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011235 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011236 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011237
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011238 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011239 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011240 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011241
11242 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11243 // allow either a mul, shift, or constant here.
11244 Value *NewIdx = 0;
11245 ConstantInt *Scale = 0;
11246 if (ArrayEltSize == 1) {
11247 NewIdx = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011248 Scale =
11249 Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011250 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011251 NewIdx = Context->getConstantInt(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011252 Scale = CI;
11253 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11254 if (Inst->getOpcode() == Instruction::Shl &&
11255 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011256 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11257 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersond672ecb2009-07-03 00:17:18 +000011258 Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011259 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011260 NewIdx = Inst->getOperand(0);
11261 } else if (Inst->getOpcode() == Instruction::Mul &&
11262 isa<ConstantInt>(Inst->getOperand(1))) {
11263 Scale = cast<ConstantInt>(Inst->getOperand(1));
11264 NewIdx = Inst->getOperand(0);
11265 }
11266 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011267
Chris Lattner7835cdd2005-09-13 18:36:04 +000011268 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011269 // out, perform the transformation. Note, we don't know whether Scale is
11270 // signed or not. We'll use unsigned version of division/modulo
11271 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011272 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011273 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011274 Scale = Context->getConstantInt(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011275 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011276 if (Scale->getZExtValue() != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011277 Constant *C =
11278 Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011279 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011280 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011281 NewIdx = InsertNewInstBefore(Sc, GEP);
11282 }
11283
11284 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011285 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011286 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011287 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011288 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011289 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011290 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11291 // The NewGEP must be pointer typed, so must the old one -> BitCast
11292 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011293 }
11294 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011295 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011296 }
Chris Lattner58407792009-01-09 04:53:57 +000011297
Chris Lattner46cd5a12009-01-09 05:44:56 +000011298 /// See if we can simplify:
11299 /// X = bitcast A to B*
11300 /// Y = gep X, <...constant indices...>
11301 /// into a gep of the original struct. This is important for SROA and alias
11302 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011303 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011304 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11305 // Determine how much the GEP moves the pointer. We are guaranteed to get
11306 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011307 ConstantInt *OffsetV =
11308 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011309 int64_t Offset = OffsetV->getSExtValue();
11310
11311 // If this GEP instruction doesn't move the pointer, just replace the GEP
11312 // with a bitcast of the real input to the dest type.
11313 if (Offset == 0) {
11314 // If the bitcast is of an allocation, and the allocation will be
11315 // converted to match the type of the cast, don't touch this.
11316 if (isa<AllocationInst>(BCI->getOperand(0))) {
11317 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11318 if (Instruction *I = visitBitCast(*BCI)) {
11319 if (I != BCI) {
11320 I->takeName(BCI);
11321 BCI->getParent()->getInstList().insert(BCI, I);
11322 ReplaceInstUsesWith(*BCI, I);
11323 }
11324 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011325 }
Chris Lattner58407792009-01-09 04:53:57 +000011326 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011327 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011328 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011329
11330 // Otherwise, if the offset is non-zero, we need to find out if there is a
11331 // field at Offset in 'A's type. If so, we can pull the cast through the
11332 // GEP.
11333 SmallVector<Value*, 8> NewIndices;
11334 const Type *InTy =
11335 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011336 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011337 Instruction *NGEP =
11338 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11339 NewIndices.end());
11340 if (NGEP->getType() == GEP.getType()) return NGEP;
11341 InsertNewInstBefore(NGEP, GEP);
11342 NGEP->takeName(&GEP);
11343 return new BitCastInst(NGEP, GEP.getType());
11344 }
Chris Lattner58407792009-01-09 04:53:57 +000011345 }
11346 }
11347
Chris Lattner8a2a3112001-12-14 16:52:21 +000011348 return 0;
11349}
11350
Chris Lattner0864acf2002-11-04 16:18:53 +000011351Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11352 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011353 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011354 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11355 const Type *NewTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000011356 Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011357 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011358
11359 // Create and insert the replacement instruction...
11360 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +000011361 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011362 else {
11363 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Owen Anderson50dead02009-07-15 23:53:25 +000011364 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011365 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011366
11367 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011368
Chris Lattner0864acf2002-11-04 16:18:53 +000011369 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011370 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011371 //
11372 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011373 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011374
11375 // Now that I is pointing to the first non-allocation-inst in the block,
11376 // insert our getelementptr instruction...
11377 //
Owen Andersond672ecb2009-07-03 00:17:18 +000011378 Value *NullIdx = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011379 Value *Idx[2];
11380 Idx[0] = NullIdx;
11381 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011382 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11383 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011384
11385 // Now make everything use the getelementptr instead of the original
11386 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011387 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011388 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011389 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011390 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011391 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011392
Dan Gohman6893cd72009-01-13 20:18:38 +000011393 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11394 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011395 // Note that we only do this for alloca's, because malloc should allocate
11396 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011397 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersond672ecb2009-07-03 00:17:18 +000011398 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011399
11400 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11401 if (AI.getAlignment() == 0)
11402 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11403 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011404
Chris Lattner0864acf2002-11-04 16:18:53 +000011405 return 0;
11406}
11407
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011408Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11409 Value *Op = FI.getOperand(0);
11410
Chris Lattner17be6352004-10-18 02:59:09 +000011411 // free undef -> unreachable.
11412 if (isa<UndefValue>(Op)) {
11413 // Insert a new store to null because we cannot modify the CFG here.
Owen Andersond672ecb2009-07-03 00:17:18 +000011414 new StoreInst(Context->getConstantIntTrue(),
11415 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011416 return EraseInstFromFunction(FI);
11417 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011418
Chris Lattner6160e852004-02-28 04:57:37 +000011419 // If we have 'free null' delete the instruction. This can happen in stl code
11420 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011421 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011422 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011423
11424 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11425 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11426 FI.setOperand(0, CI->getOperand(0));
11427 return &FI;
11428 }
11429
11430 // Change free (gep X, 0,0,0,0) into free(X)
11431 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11432 if (GEPI->hasAllZeroIndices()) {
11433 AddToWorkList(GEPI);
11434 FI.setOperand(0, GEPI->getOperand(0));
11435 return &FI;
11436 }
11437 }
11438
11439 // Change free(malloc) into nothing, if the malloc has a single use.
11440 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11441 if (MI->hasOneUse()) {
11442 EraseInstFromFunction(FI);
11443 return EraseInstFromFunction(*MI);
11444 }
Chris Lattner6160e852004-02-28 04:57:37 +000011445
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011446 return 0;
11447}
11448
11449
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011450/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011451static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011452 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011453 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011454 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011455 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011456
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011457 if (TD) {
11458 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11459 // Instead of loading constant c string, use corresponding integer value
11460 // directly if string length is small enough.
11461 std::string Str;
11462 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11463 unsigned len = Str.length();
11464 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11465 unsigned numBits = Ty->getPrimitiveSizeInBits();
11466 // Replace LI with immediate integer store.
11467 if ((numBits >> 3) == len + 1) {
11468 APInt StrVal(numBits, 0);
11469 APInt SingleChar(numBits, 0);
11470 if (TD->isLittleEndian()) {
11471 for (signed i = len-1; i >= 0; i--) {
11472 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11473 StrVal = (StrVal << 8) | SingleChar;
11474 }
11475 } else {
11476 for (unsigned i = 0; i < len; i++) {
11477 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11478 StrVal = (StrVal << 8) | SingleChar;
11479 }
11480 // Append NULL at the end.
11481 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011482 StrVal = (StrVal << 8) | SingleChar;
11483 }
Owen Andersond672ecb2009-07-03 00:17:18 +000011484 Value *NL = Context->getConstantInt(StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011485 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011486 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011487 }
11488 }
11489 }
11490
Mon P Wang6753f952009-02-07 22:19:29 +000011491 const PointerType *DestTy = cast<PointerType>(CI->getType());
11492 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011493 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011494
11495 // If the address spaces don't match, don't eliminate the cast.
11496 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11497 return 0;
11498
Chris Lattnerb89e0712004-07-13 01:49:43 +000011499 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011500
Reid Spencer42230162007-01-22 05:51:25 +000011501 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011502 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011503 // If the source is an array, the code below will not succeed. Check to
11504 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11505 // constants.
11506 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11507 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11508 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011509 Value *Idxs[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011510 Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11511 CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011512 SrcTy = cast<PointerType>(CastOp->getType());
11513 SrcPTy = SrcTy->getElementType();
11514 }
11515
Reid Spencer42230162007-01-22 05:51:25 +000011516 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011517 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011518 // Do not allow turning this into a load of an integer, which is then
11519 // casted to a pointer, this pessimizes pointer analysis a lot.
11520 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000011521 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11522 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011523
Chris Lattnerf9527852005-01-31 04:50:46 +000011524 // Okay, we are casting from one integer or pointer type to another of
11525 // the same size. Instead of casting the pointer before the load, cast
11526 // the result of the loaded value.
11527 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11528 CI->getName(),
11529 LI.isVolatile()),LI);
11530 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011531 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011532 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011533 }
11534 }
11535 return 0;
11536}
11537
Chris Lattner833b8a42003-06-26 05:06:25 +000011538Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11539 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011540
Dan Gohman9941f742007-07-20 16:34:21 +000011541 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011542 unsigned KnownAlign =
11543 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011544 if (KnownAlign >
11545 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11546 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011547 LI.setAlignment(KnownAlign);
11548
Chris Lattner37366c12005-05-01 04:24:53 +000011549 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011550 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011551 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011552 return Res;
11553
11554 // None of the following transforms are legal for volatile loads.
11555 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011556
Dan Gohman2276a7b2008-10-15 23:19:35 +000011557 // Do really simple store-to-load forwarding and load CSE, to catch cases
11558 // where there are several consequtive memory accesses to the same location,
11559 // separated by a few arithmetic operations.
11560 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011561 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11562 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011563
Christopher Lambb15147e2007-12-29 07:56:53 +000011564 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11565 const Value *GEPI0 = GEPI->getOperand(0);
11566 // TODO: Consider a target hook for valid address spaces for this xform.
11567 if (isa<ConstantPointerNull>(GEPI0) &&
11568 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011569 // Insert a new store to null instruction before the load to indicate
11570 // that this code is not reachable. We do this instead of inserting
11571 // an unreachable instruction directly because we cannot modify the
11572 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011573 new StoreInst(Context->getUndef(LI.getType()),
11574 Context->getNullValue(Op->getType()), &LI);
11575 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011576 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011577 }
Chris Lattner37366c12005-05-01 04:24:53 +000011578
Chris Lattnere87597f2004-10-16 18:11:37 +000011579 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011580 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011581 // TODO: Consider a target hook for valid address spaces for this xform.
11582 if (isa<UndefValue>(C) || (C->isNullValue() &&
11583 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011584 // Insert a new store to null instruction before the load to indicate that
11585 // this code is not reachable. We do this instead of inserting an
11586 // unreachable instruction directly because we cannot modify the CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011587 new StoreInst(Context->getUndef(LI.getType()),
11588 Context->getNullValue(Op->getType()), &LI);
11589 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011590 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011591
Chris Lattnere87597f2004-10-16 18:11:37 +000011592 // Instcombine load (constant global) into the value loaded.
11593 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011594 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011595 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011596
Chris Lattnere87597f2004-10-16 18:11:37 +000011597 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011598 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011599 if (CE->getOpcode() == Instruction::GetElementPtr) {
11600 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011601 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011602 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011603 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
11604 Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011605 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011606 if (CE->getOperand(0)->isNullValue()) {
11607 // Insert a new store to null instruction before the load to indicate
11608 // that this code is not reachable. We do this instead of inserting
11609 // an unreachable instruction directly because we cannot modify the
11610 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011611 new StoreInst(Context->getUndef(LI.getType()),
11612 Context->getNullValue(Op->getType()), &LI);
11613 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011614 }
11615
Reid Spencer3da59db2006-11-27 01:05:10 +000011616 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011617 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011618 return Res;
11619 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011620 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011621 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011622
11623 // If this load comes from anywhere in a constant global, and if the global
11624 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011625 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011626 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011627 if (GV->getInitializer()->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +000011628 return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011629 else if (isa<UndefValue>(GV->getInitializer()))
Owen Andersond672ecb2009-07-03 00:17:18 +000011630 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011631 }
11632 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011633
Chris Lattner37366c12005-05-01 04:24:53 +000011634 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011635 // Change select and PHI nodes to select values instead of addresses: this
11636 // helps alias analysis out a lot, allows many others simplifications, and
11637 // exposes redundancy in the code.
11638 //
11639 // Note that we cannot do the transformation unless we know that the
11640 // introduced loads cannot trap! Something like this is valid as long as
11641 // the condition is always false: load (select bool %C, int* null, int* %G),
11642 // but it would not be valid if we transformed it to load from null
11643 // unconditionally.
11644 //
11645 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11646 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011647 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11648 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011649 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011650 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011651 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011652 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011653 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011654 }
11655
Chris Lattner684fe212004-09-23 15:46:00 +000011656 // load (select (cond, null, P)) -> load P
11657 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11658 if (C->isNullValue()) {
11659 LI.setOperand(0, SI->getOperand(2));
11660 return &LI;
11661 }
11662
11663 // load (select (cond, P, null)) -> load P
11664 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11665 if (C->isNullValue()) {
11666 LI.setOperand(0, SI->getOperand(1));
11667 return &LI;
11668 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011669 }
11670 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011671 return 0;
11672}
11673
Reid Spencer55af2b52007-01-19 21:20:31 +000011674/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011675/// when possible. This makes it generally easy to do alias analysis and/or
11676/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011677static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11678 User *CI = cast<User>(SI.getOperand(1));
11679 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011680 LLVMContext *Context = IC.getContext();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011681
11682 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011683 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11684 if (SrcTy == 0) return 0;
11685
11686 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011687
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011688 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11689 return 0;
11690
Chris Lattner3914f722009-01-24 01:00:13 +000011691 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11692 /// to its first element. This allows us to handle things like:
11693 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11694 /// on 32-bit hosts.
11695 SmallVector<Value*, 4> NewGEPIndices;
11696
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011697 // If the source is an array, the code below will not succeed. Check to
11698 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11699 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011700 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11701 // Index through pointer.
Owen Andersond672ecb2009-07-03 00:17:18 +000011702 Constant *Zero = Context->getNullValue(Type::Int32Ty);
Chris Lattner3914f722009-01-24 01:00:13 +000011703 NewGEPIndices.push_back(Zero);
11704
11705 while (1) {
11706 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011707 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011708 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011709 NewGEPIndices.push_back(Zero);
11710 SrcPTy = STy->getElementType(0);
11711 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11712 NewGEPIndices.push_back(Zero);
11713 SrcPTy = ATy->getElementType();
11714 } else {
11715 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011716 }
Chris Lattner3914f722009-01-24 01:00:13 +000011717 }
11718
Owen Andersond672ecb2009-07-03 00:17:18 +000011719 SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011720 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011721
11722 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11723 return 0;
11724
Chris Lattner71759c42009-01-16 20:12:52 +000011725 // If the pointers point into different address spaces or if they point to
11726 // values with different sizes, we can't do the transformation.
11727 if (SrcTy->getAddressSpace() !=
11728 cast<PointerType>(CI->getType())->getAddressSpace() ||
11729 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011730 IC.getTargetData().getTypeSizeInBits(DestPTy))
11731 return 0;
11732
11733 // Okay, we are casting from one integer or pointer type to another of
11734 // the same size. Instead of casting the pointer before
11735 // the store, cast the value to be stored.
11736 Value *NewCast;
11737 Value *SIOp0 = SI.getOperand(0);
11738 Instruction::CastOps opcode = Instruction::BitCast;
11739 const Type* CastSrcTy = SIOp0->getType();
11740 const Type* CastDstTy = SrcPTy;
11741 if (isa<PointerType>(CastDstTy)) {
11742 if (CastSrcTy->isInteger())
11743 opcode = Instruction::IntToPtr;
11744 } else if (isa<IntegerType>(CastDstTy)) {
11745 if (isa<PointerType>(SIOp0->getType()))
11746 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011747 }
Chris Lattner3914f722009-01-24 01:00:13 +000011748
11749 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11750 // emit a GEP to index into its first field.
11751 if (!NewGEPIndices.empty()) {
11752 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000011753 CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner3914f722009-01-24 01:00:13 +000011754 NewGEPIndices.size());
11755 else
11756 CastOp = IC.InsertNewInstBefore(
11757 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11758 NewGEPIndices.end()), SI);
11759 }
11760
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011761 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Andersond672ecb2009-07-03 00:17:18 +000011762 NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011763 else
11764 NewCast = IC.InsertNewInstBefore(
11765 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11766 SI);
11767 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011768}
11769
Chris Lattner4aebaee2008-11-27 08:56:30 +000011770/// equivalentAddressValues - Test if A and B will obviously have the same
11771/// value. This includes recognizing that %t0 and %t1 will have the same
11772/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011773/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011774/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011775/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011776/// %t2 = load i32* %t1
11777///
11778static bool equivalentAddressValues(Value *A, Value *B) {
11779 // Test if the values are trivially equivalent.
11780 if (A == B) return true;
11781
11782 // Test if the values come form identical arithmetic instructions.
11783 if (isa<BinaryOperator>(A) ||
11784 isa<CastInst>(A) ||
11785 isa<PHINode>(A) ||
11786 isa<GetElementPtrInst>(A))
11787 if (Instruction *BI = dyn_cast<Instruction>(B))
11788 if (cast<Instruction>(A)->isIdenticalTo(BI))
11789 return true;
11790
11791 // Otherwise they may not be equivalent.
11792 return false;
11793}
11794
Dale Johannesen4945c652009-03-03 21:26:39 +000011795// If this instruction has two uses, one of which is a llvm.dbg.declare,
11796// return the llvm.dbg.declare.
11797DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11798 if (!V->hasNUses(2))
11799 return 0;
11800 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11801 UI != E; ++UI) {
11802 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11803 return DI;
11804 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11805 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11806 return DI;
11807 }
11808 }
11809 return 0;
11810}
11811
Chris Lattner2f503e62005-01-31 05:36:43 +000011812Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11813 Value *Val = SI.getOperand(0);
11814 Value *Ptr = SI.getOperand(1);
11815
11816 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011817 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011818 ++NumCombined;
11819 return 0;
11820 }
Chris Lattner836692d2007-01-15 06:51:56 +000011821
11822 // If the RHS is an alloca with a single use, zapify the store, making the
11823 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011824 // If the RHS is an alloca with a two uses, the other one being a
11825 // llvm.dbg.declare, zapify the store and the declare, making the
11826 // alloca dead. We must do this to prevent declare's from affecting
11827 // codegen.
11828 if (!SI.isVolatile()) {
11829 if (Ptr->hasOneUse()) {
11830 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011831 EraseInstFromFunction(SI);
11832 ++NumCombined;
11833 return 0;
11834 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011835 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11836 if (isa<AllocaInst>(GEP->getOperand(0))) {
11837 if (GEP->getOperand(0)->hasOneUse()) {
11838 EraseInstFromFunction(SI);
11839 ++NumCombined;
11840 return 0;
11841 }
11842 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11843 EraseInstFromFunction(*DI);
11844 EraseInstFromFunction(SI);
11845 ++NumCombined;
11846 return 0;
11847 }
11848 }
11849 }
11850 }
11851 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11852 EraseInstFromFunction(*DI);
11853 EraseInstFromFunction(SI);
11854 ++NumCombined;
11855 return 0;
11856 }
Chris Lattner836692d2007-01-15 06:51:56 +000011857 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011858
Dan Gohman9941f742007-07-20 16:34:21 +000011859 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011860 unsigned KnownAlign =
11861 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011862 if (KnownAlign >
11863 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11864 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011865 SI.setAlignment(KnownAlign);
11866
Dale Johannesenacb51a32009-03-03 01:43:03 +000011867 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011868 // stores to the same location, separated by a few arithmetic operations. This
11869 // situation often occurs with bitfield accesses.
11870 BasicBlock::iterator BBI = &SI;
11871 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11872 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011873 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011874 // Don't count debug info directives, lest they affect codegen,
11875 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11876 // It is necessary for correctness to skip those that feed into a
11877 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011878 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011879 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011880 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011881 continue;
11882 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011883
11884 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11885 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011886 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11887 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011888 ++NumDeadStore;
11889 ++BBI;
11890 EraseInstFromFunction(*PrevSI);
11891 continue;
11892 }
11893 break;
11894 }
11895
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011896 // If this is a load, we have to stop. However, if the loaded value is from
11897 // the pointer we're loading and is producing the pointer we're storing,
11898 // then *this* store is dead (X = load P; store X -> P).
11899 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011900 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11901 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011902 EraseInstFromFunction(SI);
11903 ++NumCombined;
11904 return 0;
11905 }
11906 // Otherwise, this is a load from some other location. Stores before it
11907 // may not be dead.
11908 break;
11909 }
11910
Chris Lattner9ca96412006-02-08 03:25:32 +000011911 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011912 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011913 break;
11914 }
11915
11916
11917 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011918
11919 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011920 if (isa<ConstantPointerNull>(Ptr) &&
11921 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011922 if (!isa<UndefValue>(Val)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011923 SI.setOperand(0, Context->getUndef(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011924 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011925 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011926 ++NumCombined;
11927 }
11928 return 0; // Do not modify these!
11929 }
11930
11931 // store undef, Ptr -> noop
11932 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011933 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011934 ++NumCombined;
11935 return 0;
11936 }
11937
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011938 // If the pointer destination is a cast, see if we can fold the cast into the
11939 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011940 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011941 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11942 return Res;
11943 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011944 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011945 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11946 return Res;
11947
Chris Lattner408902b2005-09-12 23:23:25 +000011948
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011949 // If this store is the last instruction in the basic block (possibly
11950 // excepting debug info instructions and the pointer bitcasts that feed
11951 // into them), and if the block ends with an unconditional branch, try
11952 // to move it to the successor block.
11953 BBI = &SI;
11954 do {
11955 ++BBI;
11956 } while (isa<DbgInfoIntrinsic>(BBI) ||
11957 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011958 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011959 if (BI->isUnconditional())
11960 if (SimplifyStoreAtEndOfBlock(SI))
11961 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011962
Chris Lattner2f503e62005-01-31 05:36:43 +000011963 return 0;
11964}
11965
Chris Lattner3284d1f2007-04-15 00:07:55 +000011966/// SimplifyStoreAtEndOfBlock - Turn things like:
11967/// if () { *P = v1; } else { *P = v2 }
11968/// into a phi node with a store in the successor.
11969///
Chris Lattner31755a02007-04-15 01:02:18 +000011970/// Simplify things like:
11971/// *P = v1; if () { *P = v2; }
11972/// into a phi node with a store in the successor.
11973///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011974bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11975 BasicBlock *StoreBB = SI.getParent();
11976
11977 // Check to see if the successor block has exactly two incoming edges. If
11978 // so, see if the other predecessor contains a store to the same location.
11979 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011980 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011981
11982 // Determine whether Dest has exactly two predecessors and, if so, compute
11983 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011984 pred_iterator PI = pred_begin(DestBB);
11985 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011986 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011987 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011988 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011989 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011990 return false;
11991
11992 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011993 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011994 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011995 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011996 }
Chris Lattner31755a02007-04-15 01:02:18 +000011997 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011998 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011999
12000 // Bail out if all the relevant blocks aren't distinct (this can happen,
12001 // for example, if SI is in an infinite loop)
12002 if (StoreBB == DestBB || OtherBB == DestBB)
12003 return false;
12004
Chris Lattner31755a02007-04-15 01:02:18 +000012005 // Verify that the other block ends in a branch and is not otherwise empty.
12006 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012007 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012008 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012009 return false;
12010
Chris Lattner31755a02007-04-15 01:02:18 +000012011 // If the other block ends in an unconditional branch, check for the 'if then
12012 // else' case. there is an instruction before the branch.
12013 StoreInst *OtherStore = 0;
12014 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012015 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012016 // Skip over debugging info.
12017 while (isa<DbgInfoIntrinsic>(BBI) ||
12018 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12019 if (BBI==OtherBB->begin())
12020 return false;
12021 --BBI;
12022 }
12023 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012024 OtherStore = dyn_cast<StoreInst>(BBI);
12025 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12026 return false;
12027 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012028 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012029 // destinations is StoreBB, then we have the if/then case.
12030 if (OtherBr->getSuccessor(0) != StoreBB &&
12031 OtherBr->getSuccessor(1) != StoreBB)
12032 return false;
12033
12034 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012035 // if/then triangle. See if there is a store to the same ptr as SI that
12036 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012037 for (;; --BBI) {
12038 // Check to see if we find the matching store.
12039 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12040 if (OtherStore->getOperand(1) != SI.getOperand(1))
12041 return false;
12042 break;
12043 }
Eli Friedman6903a242008-06-13 22:02:12 +000012044 // If we find something that may be using or overwriting the stored
12045 // value, or if we run out of instructions, we can't do the xform.
12046 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012047 BBI == OtherBB->begin())
12048 return false;
12049 }
12050
12051 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012052 // make sure nothing reads or overwrites the stored value in
12053 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012054 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12055 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012056 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012057 return false;
12058 }
12059 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012060
Chris Lattner31755a02007-04-15 01:02:18 +000012061 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012062 Value *MergedVal = OtherStore->getOperand(0);
12063 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012064 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012065 PN->reserveOperandSpace(2);
12066 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012067 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12068 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012069 }
12070
12071 // Advance to a place where it is safe to insert the new store and
12072 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012073 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012074 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12075 OtherStore->isVolatile()), *BBI);
12076
12077 // Nuke the old stores.
12078 EraseInstFromFunction(SI);
12079 EraseInstFromFunction(*OtherStore);
12080 ++NumCombined;
12081 return true;
12082}
12083
Chris Lattner2f503e62005-01-31 05:36:43 +000012084
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012085Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12086 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012087 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012088 BasicBlock *TrueDest;
12089 BasicBlock *FalseDest;
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012090 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012091 !isa<Constant>(X)) {
12092 // Swap Destinations and condition...
12093 BI.setCondition(X);
12094 BI.setSuccessor(0, FalseDest);
12095 BI.setSuccessor(1, TrueDest);
12096 return &BI;
12097 }
12098
Reid Spencere4d87aa2006-12-23 06:05:41 +000012099 // Cannonicalize fcmp_one -> fcmp_oeq
12100 FCmpInst::Predicate FPred; Value *Y;
12101 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012102 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012103 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12104 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12105 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012106 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012107 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012108 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012109 // Swap Destinations and condition...
12110 BI.setCondition(NewSCC);
12111 BI.setSuccessor(0, FalseDest);
12112 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012113 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012114 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012115 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012116 return &BI;
12117 }
12118
12119 // Cannonicalize icmp_ne -> icmp_eq
12120 ICmpInst::Predicate IPred;
12121 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012122 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012123 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12124 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12125 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12126 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012127 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012128 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012129 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000012130 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012131 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012132 BI.setSuccessor(0, FalseDest);
12133 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012134 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012135 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012136 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012137 return &BI;
12138 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012139
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012140 return 0;
12141}
Chris Lattner0864acf2002-11-04 16:18:53 +000012142
Chris Lattner46238a62004-07-03 00:26:11 +000012143Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12144 Value *Cond = SI.getCondition();
12145 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12146 if (I->getOpcode() == Instruction::Add)
12147 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12148 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12149 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012150 SI.setOperand(i,
12151 Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012152 AddRHS));
12153 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000012154 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012155 return &SI;
12156 }
12157 }
12158 return 0;
12159}
12160
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012161Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012162 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012163
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012164 if (!EV.hasIndices())
12165 return ReplaceInstUsesWith(EV, Agg);
12166
12167 if (Constant *C = dyn_cast<Constant>(Agg)) {
12168 if (isa<UndefValue>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012169 return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012170
12171 if (isa<ConstantAggregateZero>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012172 return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012173
12174 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12175 // Extract the element indexed by the first index out of the constant
12176 Value *V = C->getOperand(*EV.idx_begin());
12177 if (EV.getNumIndices() > 1)
12178 // Extract the remaining indices out of the constant indexed by the
12179 // first index
12180 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12181 else
12182 return ReplaceInstUsesWith(EV, V);
12183 }
12184 return 0; // Can't handle other constants
12185 }
12186 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12187 // We're extracting from an insertvalue instruction, compare the indices
12188 const unsigned *exti, *exte, *insi, *inse;
12189 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12190 exte = EV.idx_end(), inse = IV->idx_end();
12191 exti != exte && insi != inse;
12192 ++exti, ++insi) {
12193 if (*insi != *exti)
12194 // The insert and extract both reference distinctly different elements.
12195 // This means the extract is not influenced by the insert, and we can
12196 // replace the aggregate operand of the extract with the aggregate
12197 // operand of the insert. i.e., replace
12198 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12199 // %E = extractvalue { i32, { i32 } } %I, 0
12200 // with
12201 // %E = extractvalue { i32, { i32 } } %A, 0
12202 return ExtractValueInst::Create(IV->getAggregateOperand(),
12203 EV.idx_begin(), EV.idx_end());
12204 }
12205 if (exti == exte && insi == inse)
12206 // Both iterators are at the end: Index lists are identical. Replace
12207 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12208 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12209 // with "i32 42"
12210 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12211 if (exti == exte) {
12212 // The extract list is a prefix of the insert list. i.e. replace
12213 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12214 // %E = extractvalue { i32, { i32 } } %I, 1
12215 // with
12216 // %X = extractvalue { i32, { i32 } } %A, 1
12217 // %E = insertvalue { i32 } %X, i32 42, 0
12218 // by switching the order of the insert and extract (though the
12219 // insertvalue should be left in, since it may have other uses).
12220 Value *NewEV = InsertNewInstBefore(
12221 ExtractValueInst::Create(IV->getAggregateOperand(),
12222 EV.idx_begin(), EV.idx_end()),
12223 EV);
12224 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12225 insi, inse);
12226 }
12227 if (insi == inse)
12228 // The insert list is a prefix of the extract list
12229 // We can simply remove the common indices from the extract and make it
12230 // operate on the inserted value instead of the insertvalue result.
12231 // i.e., replace
12232 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12233 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12234 // with
12235 // %E extractvalue { i32 } { i32 42 }, 0
12236 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12237 exti, exte);
12238 }
12239 // Can't simplify extracts from other values. Note that nested extracts are
12240 // already simplified implicitely by the above (extract ( extract (insert) )
12241 // will be translated into extract ( insert ( extract ) ) first and then just
12242 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012243 return 0;
12244}
12245
Chris Lattner220b0cf2006-03-05 00:22:33 +000012246/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12247/// is to leave as a vector operation.
12248static bool CheapToScalarize(Value *V, bool isConstant) {
12249 if (isa<ConstantAggregateZero>(V))
12250 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012251 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012252 if (isConstant) return true;
12253 // If all elts are the same, we can extract.
12254 Constant *Op0 = C->getOperand(0);
12255 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12256 if (C->getOperand(i) != Op0)
12257 return false;
12258 return true;
12259 }
12260 Instruction *I = dyn_cast<Instruction>(V);
12261 if (!I) return false;
12262
12263 // Insert element gets simplified to the inserted element or is deleted if
12264 // this is constant idx extract element and its a constant idx insertelt.
12265 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12266 isa<ConstantInt>(I->getOperand(2)))
12267 return true;
12268 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12269 return true;
12270 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12271 if (BO->hasOneUse() &&
12272 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12273 CheapToScalarize(BO->getOperand(1), isConstant)))
12274 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012275 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12276 if (CI->hasOneUse() &&
12277 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12278 CheapToScalarize(CI->getOperand(1), isConstant)))
12279 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012280
12281 return false;
12282}
12283
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012284/// Read and decode a shufflevector mask.
12285///
12286/// It turns undef elements into values that are larger than the number of
12287/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012288static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12289 unsigned NElts = SVI->getType()->getNumElements();
12290 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12291 return std::vector<unsigned>(NElts, 0);
12292 if (isa<UndefValue>(SVI->getOperand(2)))
12293 return std::vector<unsigned>(NElts, 2*NElts);
12294
12295 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012296 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012297 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12298 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012299 Result.push_back(NElts*2); // undef -> 8
12300 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012301 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012302 return Result;
12303}
12304
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012305/// FindScalarElement - Given a vector and an element number, see if the scalar
12306/// value is already around as a register, for example if it were inserted then
12307/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012308static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012309 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012310 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12311 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012312 unsigned Width = PTy->getNumElements();
12313 if (EltNo >= Width) // Out of range access.
Owen Andersond672ecb2009-07-03 00:17:18 +000012314 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012315
12316 if (isa<UndefValue>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012317 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012318 else if (isa<ConstantAggregateZero>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012319 return Context->getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012320 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012321 return CP->getOperand(EltNo);
12322 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12323 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012324 if (!isa<ConstantInt>(III->getOperand(2)))
12325 return 0;
12326 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012327
12328 // If this is an insert to the element we are looking for, return the
12329 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012330 if (EltNo == IIElt)
12331 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012332
12333 // Otherwise, the insertelement doesn't modify the value, recurse on its
12334 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012335 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012336 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012337 unsigned LHSWidth =
12338 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012339 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012340 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012341 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012342 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012343 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012344 else
Owen Andersond672ecb2009-07-03 00:17:18 +000012345 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012346 }
12347
12348 // Otherwise, we don't know.
12349 return 0;
12350}
12351
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012352Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012353 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012354 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012355 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012356
Dan Gohman07a96762007-07-16 14:29:03 +000012357 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012358 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012359 return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012360
Reid Spencer9d6565a2007-02-15 02:26:10 +000012361 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012362 // If vector val is constant with all elements the same, replace EI with
12363 // that element. When the elements are not identical, we cannot replace yet
12364 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012365 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012366 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012367 if (C->getOperand(i) != op0) {
12368 op0 = 0;
12369 break;
12370 }
12371 if (op0)
12372 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012373 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000012374
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012375 // If extracting a specified index from the vector, see if we can recursively
12376 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012377 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012378 unsigned IndexVal = IdxC->getZExtValue();
12379 unsigned VectorWidth =
12380 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12381
12382 // If this is extracting an invalid index, turn this into undef, to avoid
12383 // crashing the code below.
12384 if (IndexVal >= VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012385 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012386
Chris Lattner867b99f2006-10-05 06:55:50 +000012387 // This instruction only demands the single element from the input vector.
12388 // If the input vector has a single use, simplify it based on this use
12389 // property.
Chris Lattner85464092007-04-09 01:37:55 +000012390 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012391 APInt UndefElts(VectorWidth, 0);
12392 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012393 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012394 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012395 EI.setOperand(0, V);
12396 return &EI;
12397 }
12398 }
12399
Owen Andersond672ecb2009-07-03 00:17:18 +000012400 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012401 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012402
12403 // If the this extractelement is directly using a bitcast from a vector of
12404 // the same number of elements, see if we can find the source element from
12405 // it. In this case, we will end up needing to bitcast the scalars.
12406 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12407 if (const VectorType *VT =
12408 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12409 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012410 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12411 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012412 return new BitCastInst(Elt, EI.getType());
12413 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012414 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012415
Chris Lattner73fa49d2006-05-25 22:53:38 +000012416 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012417 if (I->hasOneUse()) {
12418 // Push extractelement into predecessor operation if legal and
12419 // profitable to do so
12420 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012421 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12422 if (CheapToScalarize(BO, isConstantElt)) {
12423 ExtractElementInst *newEI0 =
12424 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12425 EI.getName()+".lhs");
12426 ExtractElementInst *newEI1 =
12427 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12428 EI.getName()+".rhs");
12429 InsertNewInstBefore(newEI0, EI);
12430 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012431 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012432 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012433 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012434 unsigned AS =
12435 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012436 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +000012437 Context->getPointerType(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012438 GetElementPtrInst *GEP =
12439 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012440 InsertNewInstBefore(GEP, EI);
12441 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012442 }
12443 }
12444 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12445 // Extracting the inserted element?
12446 if (IE->getOperand(2) == EI.getOperand(1))
12447 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12448 // If the inserted and extracted elements are constants, they must not
12449 // be the same value, extract from the pre-inserted value instead.
12450 if (isa<Constant>(IE->getOperand(2)) &&
12451 isa<Constant>(EI.getOperand(1))) {
12452 AddUsesToWorkList(EI);
12453 EI.setOperand(0, IE->getOperand(0));
12454 return &EI;
12455 }
12456 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12457 // If this is extracting an element from a shufflevector, figure out where
12458 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012459 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12460 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012461 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012462 unsigned LHSWidth =
12463 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12464
12465 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012466 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012467 else if (SrcIdx < LHSWidth*2) {
12468 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012469 Src = SVI->getOperand(1);
12470 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012471 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012472 }
Owen Anderson9adc0ab2009-07-14 23:09:55 +000012473 return new ExtractElementInst(Src,
12474 Context->getConstantInt(Type::Int32Ty, SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012475 }
12476 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000012477 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012478 return 0;
12479}
12480
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012481/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12482/// elements from either LHS or RHS, return the shuffle mask and true.
12483/// Otherwise, return false.
12484static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012485 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012486 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012487 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12488 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012489 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012490
12491 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012492 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012493 return true;
12494 } else if (V == LHS) {
12495 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012496 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012497 return true;
12498 } else if (V == RHS) {
12499 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012500 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012501 return true;
12502 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12503 // If this is an insert of an extract from some other vector, include it.
12504 Value *VecOp = IEI->getOperand(0);
12505 Value *ScalarOp = IEI->getOperand(1);
12506 Value *IdxOp = IEI->getOperand(2);
12507
Chris Lattnerd929f062006-04-27 21:14:21 +000012508 if (!isa<ConstantInt>(IdxOp))
12509 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012510 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012511
12512 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12513 // Okay, we can handle this if the vector we are insertinting into is
12514 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012515 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012516 // If so, update the mask to reflect the inserted undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012517 Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012518 return true;
12519 }
12520 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12521 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012522 EI->getOperand(0)->getType() == V->getType()) {
12523 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012524 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012525
12526 // This must be extracting from either LHS or RHS.
12527 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12528 // Okay, we can handle this if the vector we are insertinting into is
12529 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012530 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012531 // If so, update the mask to reflect the inserted value.
12532 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012533 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012534 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012535 } else {
12536 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012537 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012538 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012539
12540 }
12541 return true;
12542 }
12543 }
12544 }
12545 }
12546 }
12547 // TODO: Handle shufflevector here!
12548
12549 return false;
12550}
12551
12552/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12553/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12554/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012555static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012556 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012557 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012558 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012559 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012560 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012561
12562 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012563 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012564 return V;
12565 } else if (isa<ConstantAggregateZero>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012566 Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012567 return V;
12568 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12569 // If this is an insert of an extract from some other vector, include it.
12570 Value *VecOp = IEI->getOperand(0);
12571 Value *ScalarOp = IEI->getOperand(1);
12572 Value *IdxOp = IEI->getOperand(2);
12573
12574 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12575 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12576 EI->getOperand(0)->getType() == V->getType()) {
12577 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012578 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12579 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012580
12581 // Either the extracted from or inserted into vector must be RHSVec,
12582 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012583 if (EI->getOperand(0) == RHS || RHS == 0) {
12584 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012585 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012586 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012587 Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012588 return V;
12589 }
12590
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012591 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012592 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12593 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012594 // Everything but the extracted element is replaced with the RHS.
12595 for (unsigned i = 0; i != NumElts; ++i) {
12596 if (i != InsertedIdx)
Owen Andersond672ecb2009-07-03 00:17:18 +000012597 Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012598 }
12599 return V;
12600 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012601
12602 // If this insertelement is a chain that comes from exactly these two
12603 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012604 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12605 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012606 return EI->getOperand(0);
12607
Chris Lattnerefb47352006-04-15 01:39:45 +000012608 }
12609 }
12610 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012611 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012612
12613 // Otherwise, can't do anything fancy. Return an identity vector.
12614 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012615 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012616 return V;
12617}
12618
12619Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12620 Value *VecOp = IE.getOperand(0);
12621 Value *ScalarOp = IE.getOperand(1);
12622 Value *IdxOp = IE.getOperand(2);
12623
Chris Lattner599ded12007-04-09 01:11:16 +000012624 // Inserting an undef or into an undefined place, remove this.
12625 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12626 ReplaceInstUsesWith(IE, VecOp);
12627
Chris Lattnerefb47352006-04-15 01:39:45 +000012628 // If the inserted element was extracted from some other vector, and if the
12629 // indexes are constant, try to turn this into a shufflevector operation.
12630 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12631 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12632 EI->getOperand(0)->getType() == IE.getType()) {
12633 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012634 unsigned ExtractedIdx =
12635 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012636 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012637
12638 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12639 return ReplaceInstUsesWith(IE, VecOp);
12640
12641 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersond672ecb2009-07-03 00:17:18 +000012642 return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012643
12644 // If we are extracting a value from a vector, then inserting it right
12645 // back into the same place, just use the input vector.
12646 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12647 return ReplaceInstUsesWith(IE, VecOp);
12648
12649 // We could theoretically do this for ANY input. However, doing so could
12650 // turn chains of insertelement instructions into a chain of shufflevector
12651 // instructions, and right now we do not merge shufflevectors. As such,
12652 // only do this in a situation where it is clear that there is benefit.
12653 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12654 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12655 // the values of VecOp, except then one read from EIOp0.
12656 // Build a new shuffle mask.
12657 std::vector<Constant*> Mask;
12658 if (isa<UndefValue>(VecOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000012659 Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012660 else {
12661 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Andersond672ecb2009-07-03 00:17:18 +000012662 Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012663 NumVectorElts));
12664 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012665 Mask[InsertedIdx] =
12666 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012667 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersond672ecb2009-07-03 00:17:18 +000012668 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012669 }
12670
12671 // If this insertelement isn't used by some other insertelement, turn it
12672 // (and any insertelements it points to), into one big shuffle.
12673 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12674 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012675 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012676 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12677 if (RHS == 0) RHS = Context->getUndef(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012678 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012679 return new ShuffleVectorInst(LHS, RHS,
12680 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012681 }
12682 }
12683 }
12684
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012685 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12686 APInt UndefElts(VWidth, 0);
12687 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12688 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12689 return &IE;
12690
Chris Lattnerefb47352006-04-15 01:39:45 +000012691 return 0;
12692}
12693
12694
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012695Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12696 Value *LHS = SVI.getOperand(0);
12697 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012698 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012699
12700 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012701
Chris Lattner867b99f2006-10-05 06:55:50 +000012702 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012703 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012704 return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012705
Dan Gohman488fbfc2008-09-09 18:11:14 +000012706 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012707
12708 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12709 return 0;
12710
Evan Cheng388df622009-02-03 10:05:09 +000012711 APInt UndefElts(VWidth, 0);
12712 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12713 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012714 LHS = SVI.getOperand(0);
12715 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012716 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012717 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012718
Chris Lattner863bcff2006-05-25 23:48:38 +000012719 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12720 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12721 if (LHS == RHS || isa<UndefValue>(LHS)) {
12722 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012723 // shuffle(undef,undef,mask) -> undef.
12724 return ReplaceInstUsesWith(SVI, LHS);
12725 }
12726
Chris Lattner863bcff2006-05-25 23:48:38 +000012727 // Remap any references to RHS to use LHS.
12728 std::vector<Constant*> Elts;
12729 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012730 if (Mask[i] >= 2*e)
Owen Andersond672ecb2009-07-03 00:17:18 +000012731 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012732 else {
12733 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012734 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012735 Mask[i] = 2*e; // Turn into undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012736 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman4ce96272008-08-06 18:17:32 +000012737 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012738 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Andersond672ecb2009-07-03 00:17:18 +000012739 Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012740 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012741 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012742 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012743 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +000012744 SVI.setOperand(1, Context->getUndef(RHS->getType()));
12745 SVI.setOperand(2, Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012746 LHS = SVI.getOperand(0);
12747 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012748 MadeChange = true;
12749 }
12750
Chris Lattner7b2e27922006-05-26 00:29:06 +000012751 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012752 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012753
Chris Lattner863bcff2006-05-25 23:48:38 +000012754 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12755 if (Mask[i] >= e*2) continue; // Ignore undef values.
12756 // Is this an identity shuffle of the LHS value?
12757 isLHSID &= (Mask[i] == i);
12758
12759 // Is this an identity shuffle of the RHS value?
12760 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012761 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012762
Chris Lattner863bcff2006-05-25 23:48:38 +000012763 // Eliminate identity shuffles.
12764 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12765 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012766
Chris Lattner7b2e27922006-05-26 00:29:06 +000012767 // If the LHS is a shufflevector itself, see if we can combine it with this
12768 // one without producing an unusual shuffle. Here we are really conservative:
12769 // we are absolutely afraid of producing a shuffle mask not in the input
12770 // program, because the code gen may not be smart enough to turn a merged
12771 // shuffle into two specific shuffles: it may produce worse code. As such,
12772 // we only merge two shuffles if the result is one of the two input shuffle
12773 // masks. In this case, merging the shuffles just removes one instruction,
12774 // which we know is safe. This is good for things like turning:
12775 // (splat(splat)) -> splat.
12776 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12777 if (isa<UndefValue>(RHS)) {
12778 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12779
12780 std::vector<unsigned> NewMask;
12781 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12782 if (Mask[i] >= 2*e)
12783 NewMask.push_back(2*e);
12784 else
12785 NewMask.push_back(LHSMask[Mask[i]]);
12786
12787 // If the result mask is equal to the src shuffle or this shuffle mask, do
12788 // the replacement.
12789 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012790 unsigned LHSInNElts =
12791 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012792 std::vector<Constant*> Elts;
12793 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012794 if (NewMask[i] >= LHSInNElts*2) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012795 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012796 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012797 Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012798 }
12799 }
12800 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12801 LHSSVI->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +000012802 Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012803 }
12804 }
12805 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012806
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012807 return MadeChange ? &SVI : 0;
12808}
12809
12810
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012811
Chris Lattnerea1c4542004-12-08 23:43:58 +000012812
12813/// TryToSinkInstruction - Try to move the specified instruction from its
12814/// current block into the beginning of DestBlock, which can only happen if it's
12815/// safe to move the instruction past all of the instructions between it and the
12816/// end of its block.
12817static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12818 assert(I->hasOneUse() && "Invariants didn't hold!");
12819
Chris Lattner108e9022005-10-27 17:13:11 +000012820 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012821 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012822 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012823
Chris Lattnerea1c4542004-12-08 23:43:58 +000012824 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012825 if (isa<AllocaInst>(I) && I->getParent() ==
12826 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012827 return false;
12828
Chris Lattner96a52a62004-12-09 07:14:34 +000012829 // We can only sink load instructions if there is nothing between the load and
12830 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012831 if (I->mayReadFromMemory()) {
12832 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012833 Scan != E; ++Scan)
12834 if (Scan->mayWriteToMemory())
12835 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012836 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012837
Dan Gohman02dea8b2008-05-23 21:05:58 +000012838 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012839
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012840 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012841 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012842 ++NumSunkInst;
12843 return true;
12844}
12845
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012846
12847/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12848/// all reachable code to the worklist.
12849///
12850/// This has a couple of tricks to make the code faster and more powerful. In
12851/// particular, we constant fold and DCE instructions as we go, to avoid adding
12852/// them to the worklist (this significantly speeds up instcombine on code where
12853/// many instructions are dead or constant). Additionally, if we find a branch
12854/// whose condition is a known constant, we only visit the reachable successors.
12855///
12856static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012857 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012858 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012859 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012860 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012861 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012862
Chris Lattner2c7718a2007-03-23 19:17:18 +000012863 while (!Worklist.empty()) {
12864 BB = Worklist.back();
12865 Worklist.pop_back();
12866
12867 // We have now visited this block! If we've already been here, ignore it.
12868 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012869
12870 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012871 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12872 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012873
Chris Lattner2c7718a2007-03-23 19:17:18 +000012874 // DCE instruction if trivially dead.
12875 if (isInstructionTriviallyDead(Inst)) {
12876 ++NumDeadInst;
12877 DOUT << "IC: DCE: " << *Inst;
12878 Inst->eraseFromParent();
12879 continue;
12880 }
12881
12882 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012883 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000012884 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12885 Inst->replaceAllUsesWith(C);
12886 ++NumConstProp;
12887 Inst->eraseFromParent();
12888 continue;
12889 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012890
Devang Patel7fe1dec2008-11-19 18:56:50 +000012891 // If there are two consecutive llvm.dbg.stoppoint calls then
12892 // it is likely that the optimizer deleted code in between these
12893 // two intrinsics.
12894 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12895 if (DBI_Next) {
12896 if (DBI_Prev
12897 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12898 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12899 IC.RemoveFromWorkList(DBI_Prev);
12900 DBI_Prev->eraseFromParent();
12901 }
12902 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012903 } else {
12904 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012905 }
12906
Chris Lattner2c7718a2007-03-23 19:17:18 +000012907 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012908 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012909
12910 // Recursively visit successors. If this is a branch or switch on a
12911 // constant, only visit the reachable successor.
12912 TerminatorInst *TI = BB->getTerminator();
12913 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12914 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12915 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012916 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012917 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012918 continue;
12919 }
12920 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12921 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12922 // See if this is an explicit destination.
12923 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12924 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012925 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012926 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012927 continue;
12928 }
12929
12930 // Otherwise it is the default destination.
12931 Worklist.push_back(SI->getSuccessor(0));
12932 continue;
12933 }
12934 }
12935
12936 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12937 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012938 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012939}
12940
Chris Lattnerec9c3582007-03-03 02:04:50 +000012941bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012942 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000012943 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012944
12945 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12946 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012947
Chris Lattnerb3d59702005-07-07 20:40:38 +000012948 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012949 // Do a depth-first traversal of the function, populate the worklist with
12950 // the reachable instructions. Ignore blocks that are not reachable. Keep
12951 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012952 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012953 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012954
Chris Lattnerb3d59702005-07-07 20:40:38 +000012955 // Do a quick scan over the function. If we find any blocks that are
12956 // unreachable, remove any instructions inside of them. This prevents
12957 // the instcombine code from having to deal with some bad special cases.
12958 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12959 if (!Visited.count(BB)) {
12960 Instruction *Term = BB->getTerminator();
12961 while (Term != BB->begin()) { // Remove instrs bottom-up
12962 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012963
Bill Wendlingb7427032006-11-26 09:46:52 +000012964 DOUT << "IC: DCE: " << *I;
Dale Johannesenff278b12009-03-10 21:19:49 +000012965 // A debug intrinsic shouldn't force another iteration if we weren't
12966 // going to do one without it.
12967 if (!isa<DbgInfoIntrinsic>(I)) {
12968 ++NumDeadInst;
12969 Changed = true;
12970 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012971 if (!I->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000012972 I->replaceAllUsesWith(Context->getUndef(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012973 I->eraseFromParent();
12974 }
12975 }
12976 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012977
Chris Lattnerdbab3862007-03-02 21:28:56 +000012978 while (!Worklist.empty()) {
12979 Instruction *I = RemoveOneFromWorkList();
12980 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012981
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012982 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012983 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012984 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012985 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012986 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012987 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012988
Bill Wendlingb7427032006-11-26 09:46:52 +000012989 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012990
12991 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012992 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012993 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012994 continue;
12995 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012996
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012997 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012998 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012999 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000013000
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013001 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000013002 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000013003 ReplaceInstUsesWith(*I, C);
13004
Chris Lattner62b14df2002-09-02 04:59:56 +000013005 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013006 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013007 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000013008 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013009 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000013010 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013011
Eli Friedmanfd2934f2009-07-15 22:13:34 +000013012 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013013 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000013014 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13015 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000013016 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13017 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000013018 if (NewC != CE) {
13019 i->set(NewC);
13020 Changed = true;
13021 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013022 }
13023
Chris Lattnerea1c4542004-12-08 23:43:58 +000013024 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013025 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013026 BasicBlock *BB = I->getParent();
13027 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13028 if (UserParent != BB) {
13029 bool UserIsSuccessor = false;
13030 // See if the user is one of our successors.
13031 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13032 if (*SI == UserParent) {
13033 UserIsSuccessor = true;
13034 break;
13035 }
13036
13037 // If the user is one of our immediate successors, and if that successor
13038 // only has us as a predecessors (we'd have to split the critical edge
13039 // otherwise), we can keep going.
13040 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13041 next(pred_begin(UserParent)) == pred_end(UserParent))
13042 // Okay, the CFG is simple enough, try to sink this instruction.
13043 Changed |= TryToSinkInstruction(I, UserParent);
13044 }
13045 }
13046
Chris Lattner8a2a3112001-12-14 16:52:21 +000013047 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000013048#ifndef NDEBUG
13049 std::string OrigI;
13050#endif
13051 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000013052 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013053 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013054 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013055 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013056 DOUT << "IC: Old = " << *I
13057 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000013058
Chris Lattnerf523d062004-06-09 05:08:07 +000013059 // Everything uses the new instruction now.
13060 I->replaceAllUsesWith(Result);
13061
13062 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013063 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000013064 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013065
Chris Lattner6934a042007-02-11 01:23:03 +000013066 // Move the name to the new instruction first.
13067 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013068
13069 // Insert the new instruction into the basic block...
13070 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013071 BasicBlock::iterator InsertPos = I;
13072
13073 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13074 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13075 ++InsertPos;
13076
13077 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013078
Chris Lattner00d51312004-05-01 23:27:23 +000013079 // Make sure that we reprocess all operands now that we reduced their
13080 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013081 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000013082
Chris Lattnerf523d062004-06-09 05:08:07 +000013083 // Instructions can end up on the worklist more than once. Make sure
13084 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013085 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013086
13087 // Erase the old instruction.
13088 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000013089 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013090#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000013091 DOUT << "IC: Mod = " << OrigI
13092 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000013093#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013094
Chris Lattner90ac28c2002-08-02 19:29:35 +000013095 // If the instruction was modified, it's possible that it is now dead.
13096 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013097 if (isInstructionTriviallyDead(I)) {
13098 // Make sure we process all operands now that we are reducing their
13099 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000013100 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000013101
Chris Lattner00d51312004-05-01 23:27:23 +000013102 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013103 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013104 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000013105 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000013106 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000013107 AddToWorkList(I);
13108 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013109 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013110 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013111 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013112 }
13113 }
13114
Chris Lattnerec9c3582007-03-03 02:04:50 +000013115 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000013116
13117 // Do an explicit clear, this shrinks the map if needed.
13118 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013119 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013120}
13121
Chris Lattnerec9c3582007-03-03 02:04:50 +000013122
13123bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013124 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13125
Chris Lattnerec9c3582007-03-03 02:04:50 +000013126 bool EverMadeChange = false;
13127
13128 // Iterate while there is work to do.
13129 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013130 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013131 EverMadeChange = true;
13132 return EverMadeChange;
13133}
13134
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013135FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013136 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013137}