blob: 17e372505a86c4e407aed1c90225f94ed244ca35 [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) {
Dan Gohman016de812009-07-17 23:55:56 +0000444 if (Operator *O = dyn_cast<Operator>(V)) {
445 if (O->getOpcode() == Instruction::BitCast)
446 return O->getOperand(0);
447 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
448 if (GEP->hasAllZeroIndices())
449 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000450 }
Chris Lattnereed48272005-09-13 00:40:14 +0000451 return 0;
452}
453
Reid Spencer3da59db2006-11-27 01:05:10 +0000454/// This function is a wrapper around CastInst::isEliminableCastPair. It
455/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000456static Instruction::CastOps
457isEliminableCastPair(
458 const CastInst *CI, ///< The first cast instruction
459 unsigned opcode, ///< The opcode of the second cast instruction
460 const Type *DstTy, ///< The target type for the second cast instruction
461 TargetData *TD ///< The target data for pointer size
462) {
463
464 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
465 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000466
Reid Spencer3da59db2006-11-27 01:05:10 +0000467 // Get the opcodes of the two Cast instructions
468 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
469 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000470
Chris Lattnera0e69692009-03-24 18:35:40 +0000471 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
472 DstTy, TD->getIntPtrType());
473
474 // We don't want to form an inttoptr or ptrtoint that converts to an integer
475 // type that differs from the pointer size.
476 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
477 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
478 Res = 0;
479
480 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000481}
482
483/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
484/// in any code being generated. It does not require codegen if V is simple
485/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000486static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
487 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000488 if (V->getType() == Ty || isa<Constant>(V)) return false;
489
Chris Lattner01575b72006-05-25 23:24:33 +0000490 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000491 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000492 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000493 return false;
494 return true;
495}
496
Chris Lattner4f98c562003-03-10 21:43:22 +0000497// SimplifyCommutative - This performs a few simplifications for commutative
498// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000499//
Chris Lattner4f98c562003-03-10 21:43:22 +0000500// 1. Order operands such that they are listed from right (least complex) to
501// left (most complex). This puts constants before unary operators before
502// binary operators.
503//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000504// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
505// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000506//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000507bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000508 bool Changed = false;
Owen Anderson0a5372e2009-07-13 04:09:18 +0000509 if (getComplexity(Context, I.getOperand(0)) <
510 getComplexity(Context, I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000511 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000512
Chris Lattner4f98c562003-03-10 21:43:22 +0000513 if (!I.isAssociative()) return Changed;
514 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000515 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
516 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
517 if (isa<Constant>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000518 Constant *Folded = Context->getConstantExpr(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000519 cast<Constant>(I.getOperand(1)),
520 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000521 I.setOperand(0, Op->getOperand(0));
522 I.setOperand(1, Folded);
523 return true;
524 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
525 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
526 isOnlyUse(Op) && isOnlyUse(Op1)) {
527 Constant *C1 = cast<Constant>(Op->getOperand(1));
528 Constant *C2 = cast<Constant>(Op1->getOperand(1));
529
530 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersond672ecb2009-07-03 00:17:18 +0000531 Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000532 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000533 Op1->getOperand(0),
534 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000535 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000536 I.setOperand(0, New);
537 I.setOperand(1, Folded);
538 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000539 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000540 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000541 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000542}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000543
Reid Spencere4d87aa2006-12-23 06:05:41 +0000544/// SimplifyCompare - For a CmpInst this function just orders the operands
545/// so that theyare listed from right (least complex) to left (most complex).
546/// This puts constants before unary operators before binary operators.
547bool InstCombiner::SimplifyCompare(CmpInst &I) {
Owen Anderson0a5372e2009-07-13 04:09:18 +0000548 if (getComplexity(Context, I.getOperand(0)) >=
549 getComplexity(Context, I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000550 return false;
551 I.swapOperands();
552 // Compare instructions are not associative so there's nothing else we can do.
553 return true;
554}
555
Chris Lattner8d969642003-03-10 23:06:50 +0000556// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
557// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000558//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000559static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000560 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000561 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000562
Chris Lattner0ce85802004-12-14 20:08:06 +0000563 // Constants can be considered to be negated values if they can be folded.
564 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000565 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000566
567 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
568 if (C->getType()->getElementType()->isInteger())
Owen Andersond672ecb2009-07-03 00:17:18 +0000569 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000570
Chris Lattner8d969642003-03-10 23:06:50 +0000571 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000572}
573
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000574// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
575// instruction if the LHS is a constant negative zero (which is the 'negate'
576// form).
577//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000578static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000579 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000580 return BinaryOperator::getFNegArgument(V);
581
582 // Constants can be considered to be negated values if they can be folded.
583 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000584 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000585
586 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
587 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersond672ecb2009-07-03 00:17:18 +0000588 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000589
590 return 0;
591}
592
Owen Anderson07cf79e2009-07-06 23:00:19 +0000593static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
Chris Lattner8d969642003-03-10 23:06:50 +0000594 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000595 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000596
597 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000598 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000599 return Context->getConstantInt(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000600 return 0;
601}
602
Chris Lattnerc8802d22003-03-11 00:12:48 +0000603// dyn_castFoldableMul - If this value is a multiply that can be folded into
604// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000605// non-constant operand of the multiply, and set CST to point to the multiplier.
606// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000607//
Owen Andersond672ecb2009-07-03 00:17:18 +0000608static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000609 LLVMContext *Context) {
Chris Lattner42a75512007-01-15 02:27:26 +0000610 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000611 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000612 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000613 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000614 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000615 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000616 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000617 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000618 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000619 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Owen Andersond672ecb2009-07-03 00:17:18 +0000620 CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000621 return I->getOperand(0);
622 }
623 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000624 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000625}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000626
Chris Lattner574da9b2005-01-13 20:14:25 +0000627/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
628/// expression, return it.
629static User *dyn_castGetElementPtr(Value *V) {
630 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
631 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
632 if (CE->getOpcode() == Instruction::GetElementPtr)
633 return cast<User>(V);
634 return false;
635}
636
Reid Spencer7177c3a2007-03-25 05:33:51 +0000637/// AddOne - Add one to a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000638static Constant *AddOne(Constant *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000639 return Context->getConstantExprAdd(C,
640 Context->getConstantInt(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000641}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000642/// SubOne - Subtract one from a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000643static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000644 return Context->getConstantExprSub(C,
645 Context->getConstantInt(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000646}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000647/// MultiplyOverflows - True if the multiply can not be expressed in an int
648/// this size.
Owen Andersond672ecb2009-07-03 00:17:18 +0000649static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000650 LLVMContext *Context) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000651 uint32_t W = C1->getBitWidth();
652 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
653 if (sign) {
654 LHSExt.sext(W * 2);
655 RHSExt.sext(W * 2);
656 } else {
657 LHSExt.zext(W * 2);
658 RHSExt.zext(W * 2);
659 }
660
661 APInt MulExt = LHSExt * RHSExt;
662
663 if (sign) {
664 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
665 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
666 return MulExt.slt(Min) || MulExt.sgt(Max);
667 } else
668 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
669}
Chris Lattner955f3312004-09-28 21:48:02 +0000670
Reid Spencere7816b52007-03-08 01:52:58 +0000671
Chris Lattner255d8912006-02-11 09:31:47 +0000672/// ShrinkDemandedConstant - Check to see if the specified operand of the
673/// specified instruction is a constant integer. If so, check to see if there
674/// are any bits set in the constant that are not demanded. If so, shrink the
675/// constant and return true.
676static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000677 APInt Demanded, LLVMContext *Context) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000678 assert(I && "No instruction?");
679 assert(OpNo < I->getNumOperands() && "Operand index too large");
680
681 // If the operand is not a constant integer, nothing to do.
682 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
683 if (!OpC) return false;
684
685 // If there are no bits set that aren't demanded, nothing to do.
686 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
687 if ((~Demanded & OpC->getValue()) == 0)
688 return false;
689
690 // This instruction is producing bits that are not demanded. Shrink the RHS.
691 Demanded &= OpC->getValue();
Owen Andersond672ecb2009-07-03 00:17:18 +0000692 I->setOperand(OpNo, Context->getConstantInt(Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000693 return true;
694}
695
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000696// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
697// set of known zero and one bits, compute the maximum and minimum values that
698// could have the specified known zero and known one bits, returning them in
699// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000700static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000701 const APInt& KnownOne,
702 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000703 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
704 KnownZero.getBitWidth() == Min.getBitWidth() &&
705 KnownZero.getBitWidth() == Max.getBitWidth() &&
706 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000707 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000708
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000709 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
710 // bit if it is unknown.
711 Min = KnownOne;
712 Max = KnownOne|UnknownBits;
713
Dan Gohman1c8491e2009-04-25 17:12:48 +0000714 if (UnknownBits.isNegative()) { // Sign bit is unknown
715 Min.set(Min.getBitWidth()-1);
716 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000717 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000718}
719
720// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
721// a set of known zero and one bits, compute the maximum and minimum values that
722// could have the specified known zero and known one bits, returning them in
723// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000724static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000725 const APInt &KnownOne,
726 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000727 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
728 KnownZero.getBitWidth() == Min.getBitWidth() &&
729 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000730 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000731 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000732
733 // The minimum value is when the unknown bits are all zeros.
734 Min = KnownOne;
735 // The maximum value is when the unknown bits are all ones.
736 Max = KnownOne|UnknownBits;
737}
Chris Lattner255d8912006-02-11 09:31:47 +0000738
Chris Lattner886ab6c2009-01-31 08:15:18 +0000739/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
740/// SimplifyDemandedBits knows about. See if the instruction has any
741/// properties that allow us to simplify its operands.
742bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000743 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000744 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
745 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
746
747 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
748 KnownZero, KnownOne, 0);
749 if (V == 0) return false;
750 if (V == &Inst) return true;
751 ReplaceInstUsesWith(Inst, V);
752 return true;
753}
754
755/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
756/// specified instruction operand if possible, updating it in place. It returns
757/// true if it made any change and false otherwise.
758bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
759 APInt &KnownZero, APInt &KnownOne,
760 unsigned Depth) {
761 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
762 KnownZero, KnownOne, Depth);
763 if (NewVal == 0) return false;
764 U.set(NewVal);
765 return true;
766}
767
768
769/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
770/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000771/// that only the bits set in DemandedMask of the result of V are ever used
772/// downstream. Consequently, depending on the mask and V, it may be possible
773/// to replace V with a constant or one of its operands. In such cases, this
774/// function does the replacement and returns true. In all other cases, it
775/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000776/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000777/// to be zero in the expression. These are provided to potentially allow the
778/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
779/// the expression. KnownOne and KnownZero always follow the invariant that
780/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
781/// the bits in KnownOne and KnownZero may only be accurate for those bits set
782/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
783/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000784///
785/// This returns null if it did not change anything and it permits no
786/// simplification. This returns V itself if it did some simplification of V's
787/// operands based on the information about what bits are demanded. This returns
788/// some other non-null value if it found out that V is equal to another value
789/// in the context where the specified bits are demanded, but not for all users.
790Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
791 APInt &KnownZero, APInt &KnownOne,
792 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000793 assert(V != 0 && "Null pointer of Value???");
794 assert(Depth <= 6 && "Limit Search Depth");
795 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000796 const Type *VTy = V->getType();
797 assert((TD || !isa<PointerType>(VTy)) &&
798 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000799 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
800 (!VTy->isIntOrIntVector() ||
801 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000802 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000803 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000804 "Value *V, DemandedMask, KnownZero and KnownOne "
805 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000806 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
807 // We know all of the bits for a constant!
808 KnownOne = CI->getValue() & DemandedMask;
809 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000810 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000811 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000812 if (isa<ConstantPointerNull>(V)) {
813 // We know all of the bits for a constant!
814 KnownOne.clear();
815 KnownZero = DemandedMask;
816 return 0;
817 }
818
Chris Lattner08d2cc72009-01-31 07:26:06 +0000819 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000820 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000821 if (DemandedMask == 0) { // Not demanding any bits from V.
822 if (isa<UndefValue>(V))
823 return 0;
Owen Andersond672ecb2009-07-03 00:17:18 +0000824 return Context->getUndef(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000825 }
826
Chris Lattner4598c942009-01-31 08:24:16 +0000827 if (Depth == 6) // Limit search depth.
828 return 0;
829
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000830 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
831 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
832
Dan Gohman1c8491e2009-04-25 17:12:48 +0000833 Instruction *I = dyn_cast<Instruction>(V);
834 if (!I) {
835 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
836 return 0; // Only analyze instructions.
837 }
838
Chris Lattner4598c942009-01-31 08:24:16 +0000839 // If there are multiple uses of this value and we aren't at the root, then
840 // we can't do any simplifications of the operands, because DemandedMask
841 // only reflects the bits demanded by *one* of the users.
842 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000843 // Despite the fact that we can't simplify this instruction in all User's
844 // context, we can at least compute the knownzero/knownone bits, and we can
845 // do simplifications that apply to *just* the one user if we know that
846 // this instruction has a simpler value in that context.
847 if (I->getOpcode() == Instruction::And) {
848 // If either the LHS or the RHS are Zero, the result is zero.
849 ComputeMaskedBits(I->getOperand(1), DemandedMask,
850 RHSKnownZero, RHSKnownOne, Depth+1);
851 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
852 LHSKnownZero, LHSKnownOne, Depth+1);
853
854 // If all of the demanded bits are known 1 on one side, return the other.
855 // These bits cannot contribute to the result of the 'and' in this
856 // context.
857 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
858 (DemandedMask & ~LHSKnownZero))
859 return I->getOperand(0);
860 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
861 (DemandedMask & ~RHSKnownZero))
862 return I->getOperand(1);
863
864 // If all of the demanded bits in the inputs are known zeros, return zero.
865 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000866 return Context->getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000867
868 } else if (I->getOpcode() == Instruction::Or) {
869 // We can simplify (X|Y) -> X or Y in the user's context if we know that
870 // only bits from X or Y are demanded.
871
872 // If either the LHS or the RHS are One, the result is One.
873 ComputeMaskedBits(I->getOperand(1), DemandedMask,
874 RHSKnownZero, RHSKnownOne, Depth+1);
875 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
876 LHSKnownZero, LHSKnownOne, Depth+1);
877
878 // If all of the demanded bits are known zero on one side, return the
879 // other. These bits cannot contribute to the result of the 'or' in this
880 // context.
881 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
882 (DemandedMask & ~LHSKnownOne))
883 return I->getOperand(0);
884 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
885 (DemandedMask & ~RHSKnownOne))
886 return I->getOperand(1);
887
888 // If all of the potentially set bits on one side are known to be set on
889 // the other side, just use the 'other' side.
890 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
891 (DemandedMask & (~RHSKnownZero)))
892 return I->getOperand(0);
893 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
894 (DemandedMask & (~LHSKnownZero)))
895 return I->getOperand(1);
896 }
897
Chris Lattner4598c942009-01-31 08:24:16 +0000898 // Compute the KnownZero/KnownOne bits to simplify things downstream.
899 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
900 return 0;
901 }
902
903 // If this is the root being simplified, allow it to have multiple uses,
904 // just set the DemandedMask to all bits so that we can try to simplify the
905 // operands. This allows visitTruncInst (for example) to simplify the
906 // operand of a trunc without duplicating all the logic below.
907 if (Depth == 0 && !V->hasOneUse())
908 DemandedMask = APInt::getAllOnesValue(BitWidth);
909
Reid Spencer8cb68342007-03-12 17:25:59 +0000910 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000911 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000912 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000913 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000914 case Instruction::And:
915 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000916 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
917 RHSKnownZero, RHSKnownOne, Depth+1) ||
918 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000919 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000920 return I;
921 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
922 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000923
924 // If all of the demanded bits are known 1 on one side, return the other.
925 // These bits cannot contribute to the result of the 'and'.
926 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
927 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000928 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000929 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
930 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000931 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000932
933 // If all of the demanded bits in the inputs are known zeros, return zero.
934 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000935 return Context->getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000936
937 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000938 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000939 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000940
941 // Output known-1 bits are only known if set in both the LHS & RHS.
942 RHSKnownOne &= LHSKnownOne;
943 // Output known-0 are known to be clear if zero in either the LHS | RHS.
944 RHSKnownZero |= LHSKnownZero;
945 break;
946 case Instruction::Or:
947 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000948 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
949 RHSKnownZero, RHSKnownOne, Depth+1) ||
950 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000951 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000952 return I;
953 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
954 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000955
956 // If all of the demanded bits are known zero on one side, return the other.
957 // These bits cannot contribute to the result of the 'or'.
958 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
959 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000960 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000961 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
962 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000963 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000964
965 // If all of the potentially set bits on one side are known to be set on
966 // the other side, just use the 'other' side.
967 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
968 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000969 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000970 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
971 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000972 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000973
974 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000975 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000976 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000977
978 // Output known-0 bits are only known if clear in both the LHS & RHS.
979 RHSKnownZero &= LHSKnownZero;
980 // Output known-1 are known to be set if set in either the LHS | RHS.
981 RHSKnownOne |= LHSKnownOne;
982 break;
983 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000984 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
985 RHSKnownZero, RHSKnownOne, Depth+1) ||
986 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000987 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000988 return I;
989 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
990 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000991
992 // If all of the demanded bits are known zero on one side, return the other.
993 // These bits cannot contribute to the result of the 'xor'.
994 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000995 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000996 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000997 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000998
999 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1000 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1001 (RHSKnownOne & LHSKnownOne);
1002 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1003 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1004 (RHSKnownOne & LHSKnownZero);
1005
1006 // If all of the demanded bits are known to be zero on one side or the
1007 // other, turn this into an *inclusive* or.
1008 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1009 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1010 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001011 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001012 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001013 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001014 }
1015
1016 // If all of the demanded bits on one side are known, and all of the set
1017 // bits on that side are also known to be set on the other side, turn this
1018 // into an AND, as we know the bits will be cleared.
1019 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1020 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1021 // all known
1022 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001023 Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001024 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001025 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001026 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001027 }
1028 }
1029
1030 // If the RHS is a constant, see if we can simplify it.
1031 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Owen Andersond672ecb2009-07-03 00:17:18 +00001032 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001033 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001034
1035 RHSKnownZero = KnownZeroOut;
1036 RHSKnownOne = KnownOneOut;
1037 break;
1038 }
1039 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001040 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1041 RHSKnownZero, RHSKnownOne, Depth+1) ||
1042 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001043 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001044 return I;
1045 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1046 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001047
1048 // If the operands are constants, see if we can simplify them.
Owen Andersond672ecb2009-07-03 00:17:18 +00001049 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1050 ShrinkDemandedConstant(I, 2, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001051 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001052
1053 // Only known if known in both the LHS and RHS.
1054 RHSKnownOne &= LHSKnownOne;
1055 RHSKnownZero &= LHSKnownZero;
1056 break;
1057 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001058 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001059 DemandedMask.zext(truncBf);
1060 RHSKnownZero.zext(truncBf);
1061 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001062 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001063 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001064 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001065 DemandedMask.trunc(BitWidth);
1066 RHSKnownZero.trunc(BitWidth);
1067 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001068 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001069 break;
1070 }
1071 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001072 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001073 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001074
1075 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1076 if (const VectorType *SrcVTy =
1077 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1078 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1079 // Don't touch a bitcast between vectors of different element counts.
1080 return false;
1081 } else
1082 // Don't touch a scalar-to-vector bitcast.
1083 return false;
1084 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1085 // Don't touch a vector-to-scalar bitcast.
1086 return false;
1087
Chris Lattner886ab6c2009-01-31 08:15:18 +00001088 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001089 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001090 return I;
1091 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001092 break;
1093 case Instruction::ZExt: {
1094 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001095 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001096
Zhou Shengd48653a2007-03-29 04:45:55 +00001097 DemandedMask.trunc(SrcBitWidth);
1098 RHSKnownZero.trunc(SrcBitWidth);
1099 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001100 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001101 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001102 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001103 DemandedMask.zext(BitWidth);
1104 RHSKnownZero.zext(BitWidth);
1105 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001106 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001107 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001108 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001109 break;
1110 }
1111 case Instruction::SExt: {
1112 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001113 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001114
Reid Spencer8cb68342007-03-12 17:25:59 +00001115 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001116 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001117
Zhou Sheng01542f32007-03-29 02:26:30 +00001118 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001119 // If any of the sign extended bits are demanded, we know that the sign
1120 // bit is demanded.
1121 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001122 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001123
Zhou Shengd48653a2007-03-29 04:45:55 +00001124 InputDemandedBits.trunc(SrcBitWidth);
1125 RHSKnownZero.trunc(SrcBitWidth);
1126 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001127 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001128 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001129 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001130 InputDemandedBits.zext(BitWidth);
1131 RHSKnownZero.zext(BitWidth);
1132 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001133 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001134
1135 // If the sign bit of the input is known set or clear, then we know the
1136 // top bits of the result.
1137
1138 // If the input sign bit is known zero, or if the NewBits are not demanded
1139 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001140 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001141 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001142 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1143 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001144 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001145 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001146 }
1147 break;
1148 }
1149 case Instruction::Add: {
1150 // Figure out what the input bits are. If the top bits of the and result
1151 // are not demanded, then the add doesn't demand them from its input
1152 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001153 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001154
1155 // If there is a constant on the RHS, there are a variety of xformations
1156 // we can do.
1157 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1158 // If null, this should be simplified elsewhere. Some of the xforms here
1159 // won't work if the RHS is zero.
1160 if (RHS->isZero())
1161 break;
1162
1163 // If the top bit of the output is demanded, demand everything from the
1164 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001165 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001166
1167 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001168 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001169 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001170 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001171
1172 // If the RHS of the add has bits set that can't affect the input, reduce
1173 // the constant.
Owen Andersond672ecb2009-07-03 00:17:18 +00001174 if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001175 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001176
1177 // Avoid excess work.
1178 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1179 break;
1180
1181 // Turn it into OR if input bits are zero.
1182 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1183 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001184 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001185 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001186 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001187 }
1188
1189 // We can say something about the output known-zero and known-one bits,
1190 // depending on potential carries from the input constant and the
1191 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1192 // bits set and the RHS constant is 0x01001, then we know we have a known
1193 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1194
1195 // To compute this, we first compute the potential carry bits. These are
1196 // the bits which may be modified. I'm not aware of a better way to do
1197 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001198 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001199 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001200
1201 // Now that we know which bits have carries, compute the known-1/0 sets.
1202
1203 // Bits are known one if they are known zero in one operand and one in the
1204 // other, and there is no input carry.
1205 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1206 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1207
1208 // Bits are known zero if they are known zero in both operands and there
1209 // is no input carry.
1210 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1211 } else {
1212 // If the high-bits of this ADD are not demanded, then it does not demand
1213 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001214 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001215 // Right fill the mask of bits for this ADD to demand the most
1216 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001217 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001218 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1219 LHSKnownZero, LHSKnownOne, Depth+1) ||
1220 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001221 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001222 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001223 }
1224 }
1225 break;
1226 }
1227 case Instruction::Sub:
1228 // If the high-bits of this SUB are not demanded, then it does not demand
1229 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001230 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001231 // Right fill the mask of bits for this SUB to demand the most
1232 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001233 uint32_t NLZ = DemandedMask.countLeadingZeros();
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 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001241 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1242 // the known zeros and ones.
1243 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001244 break;
1245 case Instruction::Shl:
1246 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001247 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001248 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001249 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001250 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001251 return I;
1252 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001253 RHSKnownZero <<= ShiftAmt;
1254 RHSKnownOne <<= ShiftAmt;
1255 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001256 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001257 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001258 }
1259 break;
1260 case Instruction::LShr:
1261 // For a logical shift right
1262 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001263 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001264
Reid Spencer8cb68342007-03-12 17:25:59 +00001265 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001266 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001267 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001268 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001269 return I;
1270 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001271 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1272 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001273 if (ShiftAmt) {
1274 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001275 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001276 RHSKnownZero |= HighBits; // high bits known zero.
1277 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001278 }
1279 break;
1280 case Instruction::AShr:
1281 // If this is an arithmetic shift right and only the low-bit is set, we can
1282 // always convert this into a logical shr, even if the shift amount is
1283 // variable. The low bit of the shift cannot be an input sign bit unless
1284 // the shift amount is >= the size of the datatype, which is undefined.
1285 if (DemandedMask == 1) {
1286 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001287 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001288 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001289 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001290 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001291
1292 // If the sign bit is the only bit demanded by this ashr, then there is no
1293 // need to do it, the shift doesn't change the high bit.
1294 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001295 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001296
1297 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001298 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001299
Reid Spencer8cb68342007-03-12 17:25:59 +00001300 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001301 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001302 // If any of the "high bits" are demanded, we should set the sign bit as
1303 // demanded.
1304 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1305 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001306 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001307 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001308 return I;
1309 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001310 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001311 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001312 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1313 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1314
1315 // Handle the sign bits.
1316 APInt SignBit(APInt::getSignBit(BitWidth));
1317 // Adjust to where it is now in the mask.
1318 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1319
1320 // If the input sign bit is known to be zero, or if none of the top bits
1321 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001322 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001323 (HighBits & ~DemandedMask) == HighBits) {
1324 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001325 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001326 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001327 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001328 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1329 RHSKnownOne |= HighBits;
1330 }
1331 }
1332 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001333 case Instruction::SRem:
1334 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001335 APInt RA = Rem->getValue().abs();
1336 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001337 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001338 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001339
Nick Lewycky8e394322008-11-02 02:41:50 +00001340 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001341 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001342 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001343 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001344 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001345
1346 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1347 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001348
1349 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001350
Chris Lattner886ab6c2009-01-31 08:15:18 +00001351 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001352 }
1353 }
1354 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001355 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001356 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1357 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001358 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1359 KnownZero2, KnownOne2, Depth+1) ||
1360 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001361 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001362 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001363
Chris Lattner455e9ab2009-01-21 18:09:24 +00001364 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001365 Leaders = std::max(Leaders,
1366 KnownZero2.countLeadingOnes());
1367 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001368 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001369 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001370 case Instruction::Call:
1371 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1372 switch (II->getIntrinsicID()) {
1373 default: break;
1374 case Intrinsic::bswap: {
1375 // If the only bits demanded come from one byte of the bswap result,
1376 // just shift the input byte into position to eliminate the bswap.
1377 unsigned NLZ = DemandedMask.countLeadingZeros();
1378 unsigned NTZ = DemandedMask.countTrailingZeros();
1379
1380 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1381 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1382 // have 14 leading zeros, round to 8.
1383 NLZ &= ~7;
1384 NTZ &= ~7;
1385 // If we need exactly one byte, we can do this transformation.
1386 if (BitWidth-NLZ-NTZ == 8) {
1387 unsigned ResultBit = NTZ;
1388 unsigned InputBit = BitWidth-NTZ-8;
1389
1390 // Replace this with either a left or right shift to get the byte into
1391 // the right place.
1392 Instruction *NewVal;
1393 if (InputBit > ResultBit)
1394 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00001395 Context->getConstantInt(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001396 else
1397 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00001398 Context->getConstantInt(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001399 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001400 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001401 }
1402
1403 // TODO: Could compute known zero/one bits based on the input.
1404 break;
1405 }
1406 }
1407 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001408 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001409 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001410 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001411
1412 // If the client is only demanding bits that we know, return the known
1413 // constant.
Dan Gohman1c8491e2009-04-25 17:12:48 +00001414 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001415 Constant *C = Context->getConstantInt(RHSKnownOne);
Dan Gohman1c8491e2009-04-25 17:12:48 +00001416 if (isa<PointerType>(V->getType()))
Owen Andersond672ecb2009-07-03 00:17:18 +00001417 C = Context->getConstantExprIntToPtr(C, V->getType());
Dan Gohman1c8491e2009-04-25 17:12:48 +00001418 return C;
1419 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001420 return false;
1421}
1422
Chris Lattner867b99f2006-10-05 06:55:50 +00001423
Mon P Wangaeb06d22008-11-10 04:46:22 +00001424/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001425/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001426/// actually used by the caller. This method analyzes which elements of the
1427/// operand are undef and returns that information in UndefElts.
1428///
1429/// If the information about demanded elements can be used to simplify the
1430/// operation, the operation is simplified, then the resultant value is
1431/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001432Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1433 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001434 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001435 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001436 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001437 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001438
1439 if (isa<UndefValue>(V)) {
1440 // If the entire vector is undefined, just return this info.
1441 UndefElts = EltMask;
1442 return 0;
1443 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1444 UndefElts = EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001445 return Context->getUndef(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001446 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001447
Chris Lattner867b99f2006-10-05 06:55:50 +00001448 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001449 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1450 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001451 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001452
1453 std::vector<Constant*> Elts;
1454 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001455 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001456 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001457 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001458 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1459 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001460 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001461 } else { // Otherwise, defined.
1462 Elts.push_back(CP->getOperand(i));
1463 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001464
Chris Lattner867b99f2006-10-05 06:55:50 +00001465 // If we changed the constant, return it.
Owen Andersond672ecb2009-07-03 00:17:18 +00001466 Constant *NewCP = Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001467 return NewCP != CP ? NewCP : 0;
1468 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001469 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001470 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001471
1472 // Check if this is identity. If so, return 0 since we are not simplifying
1473 // anything.
1474 if (DemandedElts == ((1ULL << VWidth) -1))
1475 return 0;
1476
Reid Spencer9d6565a2007-02-15 02:26:10 +00001477 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001478 Constant *Zero = Context->getNullValue(EltTy);
1479 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001480 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001481 for (unsigned i = 0; i != VWidth; ++i) {
1482 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1483 Elts.push_back(Elt);
1484 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001485 UndefElts = DemandedElts ^ EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001486 return Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001487 }
1488
Dan Gohman488fbfc2008-09-09 18:11:14 +00001489 // Limit search depth.
1490 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001491 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001492
1493 // If multiple users are using the root value, procede with
1494 // simplification conservatively assuming that all elements
1495 // are needed.
1496 if (!V->hasOneUse()) {
1497 // Quit if we find multiple users of a non-root value though.
1498 // They'll be handled when it's their turn to be visited by
1499 // the main instcombine process.
1500 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001501 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001502 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001503
1504 // Conservatively assume that all elements are needed.
1505 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001506 }
1507
1508 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001509 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001510
1511 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001512 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001513 Value *TmpV;
1514 switch (I->getOpcode()) {
1515 default: break;
1516
1517 case Instruction::InsertElement: {
1518 // If this is a variable index, we don't know which element it overwrites.
1519 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001520 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001521 if (Idx == 0) {
1522 // Note that we can't propagate undef elt info, because we don't know
1523 // which elt is getting updated.
1524 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1525 UndefElts2, Depth+1);
1526 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1527 break;
1528 }
1529
1530 // If this is inserting an element that isn't demanded, remove this
1531 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001532 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001533 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001534 return AddSoonDeadInstToWorklist(*I, 0);
1535
1536 // Otherwise, the element inserted overwrites whatever was there, so the
1537 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001538 APInt DemandedElts2 = DemandedElts;
1539 DemandedElts2.clear(IdxNo);
1540 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001541 UndefElts, Depth+1);
1542 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1543
1544 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001545 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001546 break;
1547 }
1548 case Instruction::ShuffleVector: {
1549 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001550 uint64_t LHSVWidth =
1551 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001552 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001553 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001554 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001555 unsigned MaskVal = Shuffle->getMaskValue(i);
1556 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001557 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001558 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001559 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001560 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001561 else
Evan Cheng388df622009-02-03 10:05:09 +00001562 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001563 }
1564 }
1565 }
1566
Nate Begeman7b254672009-02-11 22:36:25 +00001567 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001568 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001569 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001570 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1571
Nate Begeman7b254672009-02-11 22:36:25 +00001572 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001573 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1574 UndefElts3, Depth+1);
1575 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1576
1577 bool NewUndefElts = false;
1578 for (unsigned i = 0; i < VWidth; i++) {
1579 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001580 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001581 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001582 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001583 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001584 NewUndefElts = true;
1585 UndefElts.set(i);
1586 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001587 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001588 if (UndefElts3[MaskVal - LHSVWidth]) {
1589 NewUndefElts = true;
1590 UndefElts.set(i);
1591 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001592 }
1593 }
1594
1595 if (NewUndefElts) {
1596 // Add additional discovered undefs.
1597 std::vector<Constant*> Elts;
1598 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001599 if (UndefElts[i])
Owen Andersond672ecb2009-07-03 00:17:18 +00001600 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001601 else
Owen Andersond672ecb2009-07-03 00:17:18 +00001602 Elts.push_back(Context->getConstantInt(Type::Int32Ty,
Dan Gohman488fbfc2008-09-09 18:11:14 +00001603 Shuffle->getMaskValue(i)));
1604 }
Owen Andersond672ecb2009-07-03 00:17:18 +00001605 I->setOperand(2, Context->getConstantVector(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001606 MadeChange = true;
1607 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001608 break;
1609 }
Chris Lattner69878332007-04-14 22:29:23 +00001610 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001611 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001612 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1613 if (!VTy) break;
1614 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001615 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001616 unsigned Ratio;
1617
1618 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001619 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001620 // elements as are demanded of us.
1621 Ratio = 1;
1622 InputDemandedElts = DemandedElts;
1623 } else if (VWidth > InVWidth) {
1624 // Untested so far.
1625 break;
1626
1627 // If there are more elements in the result than there are in the source,
1628 // then an input element is live if any of the corresponding output
1629 // elements are live.
1630 Ratio = VWidth/InVWidth;
1631 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001632 if (DemandedElts[OutIdx])
1633 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001634 }
1635 } else {
1636 // Untested so far.
1637 break;
1638
1639 // If there are more elements in the source than there are in the result,
1640 // then an input element is live if the corresponding output element is
1641 // live.
1642 Ratio = InVWidth/VWidth;
1643 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001644 if (DemandedElts[InIdx/Ratio])
1645 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001646 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001647
Chris Lattner69878332007-04-14 22:29:23 +00001648 // div/rem demand all inputs, because they don't want divide by zero.
1649 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1650 UndefElts2, Depth+1);
1651 if (TmpV) {
1652 I->setOperand(0, TmpV);
1653 MadeChange = true;
1654 }
1655
1656 UndefElts = UndefElts2;
1657 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001658 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001659 // If there are more elements in the result than there are in the source,
1660 // then an output element is undef if the corresponding input element is
1661 // undef.
1662 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001663 if (UndefElts2[OutIdx/Ratio])
1664 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001665 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001666 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001667 // If there are more elements in the source than there are in the result,
1668 // then a result element is undef if all of the corresponding input
1669 // elements are undef.
1670 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1671 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001672 if (!UndefElts2[InIdx]) // Not undef?
1673 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001674 }
1675 break;
1676 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001677 case Instruction::And:
1678 case Instruction::Or:
1679 case Instruction::Xor:
1680 case Instruction::Add:
1681 case Instruction::Sub:
1682 case Instruction::Mul:
1683 // div/rem demand all inputs, because they don't want divide by zero.
1684 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1685 UndefElts, Depth+1);
1686 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1687 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1688 UndefElts2, Depth+1);
1689 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1690
1691 // Output elements are undefined if both are undefined. Consider things
1692 // like undef&0. The result is known zero, not undef.
1693 UndefElts &= UndefElts2;
1694 break;
1695
1696 case Instruction::Call: {
1697 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1698 if (!II) break;
1699 switch (II->getIntrinsicID()) {
1700 default: break;
1701
1702 // Binary vector operations that work column-wise. A dest element is a
1703 // function of the corresponding input elements from the two inputs.
1704 case Intrinsic::x86_sse_sub_ss:
1705 case Intrinsic::x86_sse_mul_ss:
1706 case Intrinsic::x86_sse_min_ss:
1707 case Intrinsic::x86_sse_max_ss:
1708 case Intrinsic::x86_sse2_sub_sd:
1709 case Intrinsic::x86_sse2_mul_sd:
1710 case Intrinsic::x86_sse2_min_sd:
1711 case Intrinsic::x86_sse2_max_sd:
1712 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1713 UndefElts, Depth+1);
1714 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1715 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1716 UndefElts2, Depth+1);
1717 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1718
1719 // If only the low elt is demanded and this is a scalarizable intrinsic,
1720 // scalarize it now.
1721 if (DemandedElts == 1) {
1722 switch (II->getIntrinsicID()) {
1723 default: break;
1724 case Intrinsic::x86_sse_sub_ss:
1725 case Intrinsic::x86_sse_mul_ss:
1726 case Intrinsic::x86_sse2_sub_sd:
1727 case Intrinsic::x86_sse2_mul_sd:
1728 // TODO: Lower MIN/MAX/ABS/etc
1729 Value *LHS = II->getOperand(1);
1730 Value *RHS = II->getOperand(2);
1731 // Extract the element as scalars.
Owen Anderson9adc0ab2009-07-14 23:09:55 +00001732 LHS = InsertNewInstBefore(new ExtractElementInst(LHS,
1733 Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1734 RHS = InsertNewInstBefore(new ExtractElementInst(RHS,
1735 Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001736
1737 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001738 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001739 case Intrinsic::x86_sse_sub_ss:
1740 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001741 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001742 II->getName()), *II);
1743 break;
1744 case Intrinsic::x86_sse_mul_ss:
1745 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001746 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001747 II->getName()), *II);
1748 break;
1749 }
1750
1751 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001752 InsertElementInst::Create(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00001753 Context->getUndef(II->getType()), TmpV,
1754 Context->getConstantInt(Type::Int32Ty, 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001755 InsertNewInstBefore(New, *II);
1756 AddSoonDeadInstToWorklist(*II, 0);
1757 return New;
1758 }
1759 }
1760
1761 // Output elements are undefined if both are undefined. Consider things
1762 // like undef&0. The result is known zero, not undef.
1763 UndefElts &= UndefElts2;
1764 break;
1765 }
1766 break;
1767 }
1768 }
1769 return MadeChange ? I : 0;
1770}
1771
Dan Gohman45b4e482008-05-19 22:14:15 +00001772
Chris Lattner564a7272003-08-13 19:01:45 +00001773/// AssociativeOpt - Perform an optimization on an associative operator. This
1774/// function is designed to check a chain of associative operators for a
1775/// potential to apply a certain optimization. Since the optimization may be
1776/// applicable if the expression was reassociated, this checks the chain, then
1777/// reassociates the expression as necessary to expose the optimization
1778/// opportunity. This makes use of a special Functor, which must define
1779/// 'shouldApply' and 'apply' methods.
1780///
1781template<typename Functor>
Owen Andersond672ecb2009-07-03 00:17:18 +00001782static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001783 LLVMContext *Context) {
Chris Lattner564a7272003-08-13 19:01:45 +00001784 unsigned Opcode = Root.getOpcode();
1785 Value *LHS = Root.getOperand(0);
1786
1787 // Quick check, see if the immediate LHS matches...
1788 if (F.shouldApply(LHS))
1789 return F.apply(Root);
1790
1791 // Otherwise, if the LHS is not of the same opcode as the root, return.
1792 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001793 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001794 // Should we apply this transform to the RHS?
1795 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1796
1797 // If not to the RHS, check to see if we should apply to the LHS...
1798 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1799 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1800 ShouldApply = true;
1801 }
1802
1803 // If the functor wants to apply the optimization to the RHS of LHSI,
1804 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1805 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001806 // Now all of the instructions are in the current basic block, go ahead
1807 // and perform the reassociation.
1808 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1809
1810 // First move the selected RHS to the LHS of the root...
1811 Root.setOperand(0, LHSI->getOperand(1));
1812
1813 // Make what used to be the LHS of the root be the user of the root...
1814 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001815 if (&Root == TmpLHSI) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001816 Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001817 return 0;
1818 }
Chris Lattner65725312004-04-16 18:08:07 +00001819 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001820 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001821 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001822 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001823 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001824
1825 // Now propagate the ExtraOperand down the chain of instructions until we
1826 // get to LHSI.
1827 while (TmpLHSI != LHSI) {
1828 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001829 // Move the instruction to immediately before the chain we are
1830 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001831 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001832 ARI = NextLHSI;
1833
Chris Lattner564a7272003-08-13 19:01:45 +00001834 Value *NextOp = NextLHSI->getOperand(1);
1835 NextLHSI->setOperand(1, ExtraOperand);
1836 TmpLHSI = NextLHSI;
1837 ExtraOperand = NextOp;
1838 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001839
Chris Lattner564a7272003-08-13 19:01:45 +00001840 // Now that the instructions are reassociated, have the functor perform
1841 // the transformation...
1842 return F.apply(Root);
1843 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001844
Chris Lattner564a7272003-08-13 19:01:45 +00001845 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1846 }
1847 return 0;
1848}
1849
Dan Gohman844731a2008-05-13 00:00:25 +00001850namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001851
Nick Lewycky02d639f2008-05-23 04:34:58 +00001852// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001853struct AddRHS {
1854 Value *RHS;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001855 LLVMContext *Context;
1856 AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001857 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1858 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001859 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00001860 Context->getConstantInt(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001861 }
1862};
1863
1864// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1865// iff C1&C2 == 0
1866struct AddMaskingAnd {
1867 Constant *C2;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001868 LLVMContext *Context;
1869 AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001870 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001871 ConstantInt *C1;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00001872 return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
Owen Andersond672ecb2009-07-03 00:17:18 +00001873 Context->getConstantExprAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001874 }
1875 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001876 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001877 }
1878};
1879
Dan Gohman844731a2008-05-13 00:00:25 +00001880}
1881
Chris Lattner6e7ba452005-01-01 16:22:27 +00001882static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001883 InstCombiner *IC) {
Owen Anderson07cf79e2009-07-06 23:00:19 +00001884 LLVMContext *Context = IC->getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00001885
Reid Spencer3da59db2006-11-27 01:05:10 +00001886 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001887 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001888 }
1889
Chris Lattner2eefe512004-04-09 19:05:30 +00001890 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001891 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1892 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001893
Chris Lattner2eefe512004-04-09 19:05:30 +00001894 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1895 if (ConstIsRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00001896 return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1897 return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001898 }
1899
1900 Value *Op0 = SO, *Op1 = ConstOperand;
1901 if (!ConstIsRHS)
1902 std::swap(Op0, Op1);
1903 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001904 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001905 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001906 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00001907 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1908 Op0, Op1, SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001909 else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001910 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001911 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001912 return IC->InsertNewInstBefore(New, I);
1913}
1914
1915// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1916// constant as the other operand, try to fold the binary operator into the
1917// select arguments. This also works for Cast instructions, which obviously do
1918// not have a second operand.
1919static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1920 InstCombiner *IC) {
1921 // Don't modify shared select instructions
1922 if (!SI->hasOneUse()) return 0;
1923 Value *TV = SI->getOperand(1);
1924 Value *FV = SI->getOperand(2);
1925
1926 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001927 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001928 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001929
Chris Lattner6e7ba452005-01-01 16:22:27 +00001930 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1931 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1932
Gabor Greif051a9502008-04-06 20:25:17 +00001933 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1934 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001935 }
1936 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001937}
1938
Chris Lattner4e998b22004-09-29 05:07:12 +00001939
1940/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1941/// node as operand #0, see if we can fold the instruction into the PHI (which
1942/// is only possible if all operands to the PHI are constants).
1943Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1944 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001945 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001946 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001947
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001948 // Check to see if all of the operands of the PHI are constants. If there is
1949 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001950 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001951 BasicBlock *NonConstBB = 0;
1952 for (unsigned i = 0; i != NumPHIValues; ++i)
1953 if (!isa<Constant>(PN->getIncomingValue(i))) {
1954 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001955 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001956 NonConstBB = PN->getIncomingBlock(i);
1957
1958 // If the incoming non-constant value is in I's block, we have an infinite
1959 // loop.
1960 if (NonConstBB == I.getParent())
1961 return 0;
1962 }
1963
1964 // If there is exactly one non-constant value, we can insert a copy of the
1965 // operation in that block. However, if this is a critical edge, we would be
1966 // inserting the computation one some other paths (e.g. inside a loop). Only
1967 // do this if the pred block is unconditionally branching into the phi block.
1968 if (NonConstBB) {
1969 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1970 if (!BI || !BI->isUnconditional()) return 0;
1971 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001972
1973 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001974 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001975 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001976 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001977 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001978
1979 // Next, add all of the operands to the PHI.
1980 if (I.getNumOperands() == 2) {
1981 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001982 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001983 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001984 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001985 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersond672ecb2009-07-03 00:17:18 +00001986 InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001987 else
Owen Andersond672ecb2009-07-03 00:17:18 +00001988 InV = Context->getConstantExpr(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001989 } else {
1990 assert(PN->getIncomingBlock(i) == NonConstBB);
1991 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001992 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001993 PN->getIncomingValue(i), C, "phitmp",
1994 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001995 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00001996 InV = CmpInst::Create(*Context, CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001997 CI->getPredicate(),
1998 PN->getIncomingValue(i), C, "phitmp",
1999 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002000 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002001 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002002
Chris Lattnerdbab3862007-03-02 21:28:56 +00002003 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002004 }
2005 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002006 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002007 } else {
2008 CastInst *CI = cast<CastInst>(&I);
2009 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002010 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002011 Value *InV;
2012 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002013 InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002014 } else {
2015 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002016 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002017 I.getType(), "phitmp",
2018 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002019 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002020 }
2021 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002022 }
2023 }
2024 return ReplaceInstUsesWith(I, NewPN);
2025}
2026
Chris Lattner2454a2e2008-01-29 06:52:45 +00002027
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002028/// WillNotOverflowSignedAdd - Return true if we can prove that:
2029/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2030/// This basically requires proving that the add in the original type would not
2031/// overflow to change the sign bit or have a carry out.
2032bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2033 // There are different heuristics we can use for this. Here are some simple
2034 // ones.
2035
2036 // Add has the property that adding any two 2's complement numbers can only
2037 // have one carry bit which can change a sign. As such, if LHS and RHS each
2038 // have at least two sign bits, we know that the addition of the two values will
2039 // sign extend fine.
2040 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2041 return true;
2042
2043
2044 // If one of the operands only has one non-zero bit, and if the other operand
2045 // has a known-zero bit in a more significant place than it (not including the
2046 // sign bit) the ripple may go up to and fill the zero, but won't change the
2047 // sign. For example, (X & ~4) + 1.
2048
2049 // TODO: Implement.
2050
2051 return false;
2052}
2053
Chris Lattner2454a2e2008-01-29 06:52:45 +00002054
Chris Lattner7e708292002-06-25 16:13:24 +00002055Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002056 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002057 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002058
Chris Lattner66331a42004-04-10 22:01:55 +00002059 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002060 // X + undef -> undef
2061 if (isa<UndefValue>(RHS))
2062 return ReplaceInstUsesWith(I, RHS);
2063
Chris Lattner66331a42004-04-10 22:01:55 +00002064 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002065 if (RHSC->isNullValue())
2066 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002067
Chris Lattner66331a42004-04-10 22:01:55 +00002068 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002069 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002070 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002071 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002072 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002073 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002074
2075 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2076 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002077 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002078 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002079
Eli Friedman709b33d2009-07-13 22:27:52 +00002080 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002081 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Eli Friedman709b33d2009-07-13 22:27:52 +00002082 if (ZI->getSrcTy() == Type::Int1Ty)
2083 return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002084 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002085
2086 if (isa<PHINode>(LHS))
2087 if (Instruction *NV = FoldOpIntoPhi(I))
2088 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002089
Chris Lattner4f637d42006-01-06 17:59:59 +00002090 ConstantInt *XorRHS = 0;
2091 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002092 if (isa<ConstantInt>(RHSC) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002093 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002094 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002095 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002096
Zhou Sheng4351c642007-04-02 08:20:41 +00002097 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002098 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2099 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002100 do {
2101 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002102 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2103 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002104 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2105 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002106 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002107 if (!MaskedValueIsZero(XorLHS,
2108 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002109 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002110 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002111 }
2112 }
2113 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002114 C0080Val = APIntOps::lshr(C0080Val, Size);
2115 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2116 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002117
Reid Spencer35c38852007-03-28 01:36:16 +00002118 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002119 // with funny bit widths then this switch statement should be removed. It
2120 // is just here to get the size of the "middle" type back up to something
2121 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002122 const Type *MiddleType = 0;
2123 switch (Size) {
2124 default: break;
2125 case 32: MiddleType = Type::Int32Ty; break;
2126 case 16: MiddleType = Type::Int16Ty; break;
2127 case 8: MiddleType = Type::Int8Ty; break;
2128 }
2129 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002130 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002131 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002132 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002133 }
2134 }
Chris Lattner66331a42004-04-10 22:01:55 +00002135 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002136
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002137 if (I.getType() == Type::Int1Ty)
2138 return BinaryOperator::CreateXor(LHS, RHS);
2139
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002140 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002141 if (I.getType()->isInteger()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002142 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2143 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002144
2145 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2146 if (RHSI->getOpcode() == Instruction::Sub)
2147 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2148 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2149 }
2150 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2151 if (LHSI->getOpcode() == Instruction::Sub)
2152 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2153 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2154 }
Robert Bocchino71698282004-07-27 21:02:21 +00002155 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002156
Chris Lattner5c4afb92002-05-08 22:46:53 +00002157 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002158 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002159 if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002160 if (LHS->getType()->isIntOrIntVector()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002161 if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002162 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002163 InsertNewInstBefore(NewAdd, I);
Owen Anderson0a5372e2009-07-13 04:09:18 +00002164 return BinaryOperator::CreateNeg(*Context, NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002165 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002166 }
2167
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002168 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002169 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002170
2171 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002172 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002173 if (Value *V = dyn_castNegVal(RHS, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002174 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002175
Misha Brukmanfd939082005-04-21 23:48:37 +00002176
Chris Lattner50af16a2004-11-13 19:50:12 +00002177 ConstantInt *C2;
Owen Andersond672ecb2009-07-03 00:17:18 +00002178 if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002179 if (X == RHS) // X*C + X --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002180 return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002181
2182 // X*C1 + X*C2 --> X * (C1+C2)
2183 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002184 if (X == dyn_castFoldableMul(RHS, C1, Context))
2185 return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002186 }
2187
2188 // X + X*C --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002189 if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2190 return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002191
Chris Lattnere617c9e2007-01-05 02:17:46 +00002192 // X + ~X --> -1 since ~X = -X-1
Owen Andersond672ecb2009-07-03 00:17:18 +00002193 if (dyn_castNotVal(LHS, Context) == RHS ||
2194 dyn_castNotVal(RHS, Context) == LHS)
2195 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002196
Chris Lattnerad3448c2003-02-18 19:57:07 +00002197
Chris Lattner564a7272003-08-13 19:01:45 +00002198 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002199 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002200 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002201 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002202
2203 // A+B --> A|B iff A and B have no bits set in common.
2204 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2205 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2206 APInt LHSKnownOne(IT->getBitWidth(), 0);
2207 APInt LHSKnownZero(IT->getBitWidth(), 0);
2208 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2209 if (LHSKnownZero != 0) {
2210 APInt RHSKnownOne(IT->getBitWidth(), 0);
2211 APInt RHSKnownZero(IT->getBitWidth(), 0);
2212 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2213
2214 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002215 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002216 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002217 }
2218 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002219
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002220 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002221 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002222 Value *W, *X, *Y, *Z;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002223 if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2224 match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002225 if (W != Y) {
2226 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002227 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002228 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002229 std::swap(W, X);
2230 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002231 std::swap(Y, Z);
2232 std::swap(W, X);
2233 }
2234 }
2235
2236 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002237 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002238 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002239 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002240 }
2241 }
2242 }
2243
Chris Lattner6b032052003-10-02 15:11:26 +00002244 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002245 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002246 if (match(LHS, m_Not(m_Value(X)), *Context)) // ~X + C --> (C-1) - X
Owen Andersond672ecb2009-07-03 00:17:18 +00002247 return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002248
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002249 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002250 if (LHS->hasOneUse() &&
2251 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002252 Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002253 if (Anded == CRHS) {
2254 // See if all bits from the first bit set in the Add RHS up are included
2255 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002256 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002257
2258 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002259 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002260
2261 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002262 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002263
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002264 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2265 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002266 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002267 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002268 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002269 }
2270 }
2271 }
2272
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002273 // Try to fold constant add into select arguments.
2274 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002275 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002276 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002277 }
2278
Chris Lattner42790482007-12-20 01:56:58 +00002279 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002280 {
2281 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002282 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002283 if (!SI) {
2284 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002285 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002286 }
Chris Lattner42790482007-12-20 01:56:58 +00002287 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002288 Value *TV = SI->getTrueValue();
2289 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002290 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002291
2292 // Can we fold the add into the argument of the select?
2293 // We check both true and false select arguments for a matching subtract.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002294 if (match(FV, m_Zero(), *Context) &&
2295 match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002296 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002297 return SelectInst::Create(SI->getCondition(), N, A);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002298 if (match(TV, m_Zero(), *Context) &&
2299 match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002300 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002301 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002302 }
2303 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002304
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002305 // Check for (add (sext x), y), see if we can merge this into an
2306 // integer add followed by a sext.
2307 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2308 // (add (sext x), cst) --> (sext (add x, cst'))
2309 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2310 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002311 Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002312 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002313 Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002314 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2315 // Insert the new, smaller add.
2316 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2317 CI, "addconv");
2318 InsertNewInstBefore(NewAdd, I);
2319 return new SExtInst(NewAdd, I.getType());
2320 }
2321 }
2322
2323 // (add (sext x), (sext y)) --> (sext (add int x, y))
2324 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2325 // Only do this if x/y have the same type, if at last one of them has a
2326 // single use (so we don't increase the number of sexts), and if the
2327 // integer add will not overflow.
2328 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2329 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2330 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2331 RHSConv->getOperand(0))) {
2332 // Insert the new integer add.
2333 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2334 RHSConv->getOperand(0),
2335 "addconv");
2336 InsertNewInstBefore(NewAdd, I);
2337 return new SExtInst(NewAdd, I.getType());
2338 }
2339 }
2340 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002341
2342 return Changed ? &I : 0;
2343}
2344
2345Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2346 bool Changed = SimplifyCommutative(I);
2347 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2348
2349 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2350 // X + 0 --> X
2351 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002352 if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002353 (I.getType())->getValueAPF()))
2354 return ReplaceInstUsesWith(I, LHS);
2355 }
2356
2357 if (isa<PHINode>(LHS))
2358 if (Instruction *NV = FoldOpIntoPhi(I))
2359 return NV;
2360 }
2361
2362 // -A + B --> B - A
2363 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002364 if (Value *LHSV = dyn_castFNegVal(LHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002365 return BinaryOperator::CreateFSub(RHS, LHSV);
2366
2367 // A + -B --> A - B
2368 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002369 if (Value *V = dyn_castFNegVal(RHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002370 return BinaryOperator::CreateFSub(LHS, V);
2371
2372 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2373 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2374 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2375 return ReplaceInstUsesWith(I, LHS);
2376
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002377 // Check for (add double (sitofp x), y), see if we can merge this into an
2378 // integer add followed by a promotion.
2379 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2380 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2381 // ... if the constant fits in the integer value. This is useful for things
2382 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2383 // requires a constant pool load, and generally allows the add to be better
2384 // instcombined.
2385 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2386 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002387 Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002388 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002389 Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002390 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2391 // Insert the new integer add.
2392 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2393 CI, "addconv");
2394 InsertNewInstBefore(NewAdd, I);
2395 return new SIToFPInst(NewAdd, I.getType());
2396 }
2397 }
2398
2399 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2400 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2401 // Only do this if x/y have the same type, if at last one of them has a
2402 // single use (so we don't increase the number of int->fp conversions),
2403 // and if the integer add will not overflow.
2404 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2405 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2406 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2407 RHSConv->getOperand(0))) {
2408 // Insert the new integer add.
2409 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2410 RHSConv->getOperand(0),
2411 "addconv");
2412 InsertNewInstBefore(NewAdd, I);
2413 return new SIToFPInst(NewAdd, I.getType());
2414 }
2415 }
2416 }
2417
Chris Lattner7e708292002-06-25 16:13:24 +00002418 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002419}
2420
Chris Lattner7e708292002-06-25 16:13:24 +00002421Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002422 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002423
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002424 if (Op0 == Op1) // sub X, X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002425 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002426
Chris Lattner233f7dc2002-08-12 21:17:25 +00002427 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002428 if (Value *V = dyn_castNegVal(Op1, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002429 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002430
Chris Lattnere87597f2004-10-16 18:11:37 +00002431 if (isa<UndefValue>(Op0))
2432 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2433 if (isa<UndefValue>(Op1))
2434 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2435
Chris Lattnerd65460f2003-11-05 01:06:05 +00002436 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2437 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002438 if (C->isAllOnesValue())
Owen Anderson73c6b712009-07-13 20:58:05 +00002439 return BinaryOperator::CreateNot(*Context, Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002440
Chris Lattnerd65460f2003-11-05 01:06:05 +00002441 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002442 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002443 if (match(Op1, m_Not(m_Value(X)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002444 return BinaryOperator::CreateAdd(X, AddOne(C, Context));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002445
Chris Lattner76b7a062007-01-15 07:02:54 +00002446 // -(X >>u 31) -> (X >>s 31)
2447 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002448 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002449 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002450 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002451 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002452 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002453 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002454 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002455 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002456 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002457 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002458 }
2459 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002460 }
2461 else if (SI->getOpcode() == Instruction::AShr) {
2462 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2463 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002464 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002465 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002466 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002467 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002468 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002469 }
2470 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002471 }
2472 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002473 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002474
2475 // Try to fold constant sub into select arguments.
2476 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002477 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002478 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002479
2480 // C - zext(bool) -> bool ? C - 1 : C
2481 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2482 if (ZI->getSrcTy() == Type::Int1Ty)
2483 return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002484 }
2485
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002486 if (I.getType() == Type::Int1Ty)
2487 return BinaryOperator::CreateXor(Op0, Op1);
2488
Chris Lattner43d84d62005-04-07 16:15:25 +00002489 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002490 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002491 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002492 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2493 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002494 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002495 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0),
2496 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002497 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2498 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2499 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002500 return BinaryOperator::CreateSub(
2501 Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002502 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002503 }
2504
Chris Lattnerfd059242003-10-15 16:48:29 +00002505 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002506 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2507 // is not used by anyone else...
2508 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002509 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002510 // Swap the two operands of the subexpr...
2511 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2512 Op1I->setOperand(0, IIOp1);
2513 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002514
Chris Lattnera2881962003-02-18 19:28:33 +00002515 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002516 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002517 }
2518
2519 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2520 //
2521 if (Op1I->getOpcode() == Instruction::And &&
2522 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2523 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2524
Chris Lattnerf523d062004-06-09 05:08:07 +00002525 Value *NewNot =
Owen Anderson73c6b712009-07-13 20:58:05 +00002526 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
2527 OtherOp, "B.not"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002528 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002529 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002530
Reid Spencerac5209e2006-10-16 23:08:08 +00002531 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002532 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002533 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002534 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002535 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002536 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002537 Context->getConstantExprNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002538
Chris Lattnerad3448c2003-02-18 19:57:07 +00002539 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002540 ConstantInt *C2 = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00002541 if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2542 Constant *CP1 =
2543 Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002544 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002545 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002546 }
Chris Lattner40371712002-05-09 01:29:19 +00002547 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002548 }
Chris Lattnera2881962003-02-18 19:28:33 +00002549
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002550 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2551 if (Op0I->getOpcode() == Instruction::Add) {
2552 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2553 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2554 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2555 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2556 } else if (Op0I->getOpcode() == Instruction::Sub) {
2557 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002558 return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2559 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002560 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002561 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002562
Chris Lattner50af16a2004-11-13 19:50:12 +00002563 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002564 if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002565 if (X == Op1) // X*C - X --> X * (C-1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002566 return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002567
Chris Lattner50af16a2004-11-13 19:50:12 +00002568 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Owen Andersond672ecb2009-07-03 00:17:18 +00002569 if (X == dyn_castFoldableMul(Op1, C2, Context))
2570 return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002571 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002572 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002573}
2574
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002575Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2576 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2577
2578 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002579 if (Value *V = dyn_castFNegVal(Op1, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002580 return BinaryOperator::CreateFAdd(Op0, V);
2581
2582 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2583 if (Op1I->getOpcode() == Instruction::FAdd) {
2584 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002585 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2586 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002587 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002588 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2589 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002590 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002591 }
2592
2593 return 0;
2594}
2595
Chris Lattnera0141b92007-07-15 20:42:37 +00002596/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2597/// comparison only checks the sign bit. If it only checks the sign bit, set
2598/// TrueIfSigned if the result of the comparison is true when the input value is
2599/// signed.
2600static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2601 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002602 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002603 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2604 TrueIfSigned = true;
2605 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002606 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2607 TrueIfSigned = true;
2608 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002609 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2610 TrueIfSigned = false;
2611 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002612 case ICmpInst::ICMP_UGT:
2613 // True if LHS u> RHS and RHS == high-bit-mask - 1
2614 TrueIfSigned = true;
2615 return RHS->getValue() ==
2616 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2617 case ICmpInst::ICMP_UGE:
2618 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2619 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002620 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002621 default:
2622 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002623 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002624}
2625
Chris Lattner7e708292002-06-25 16:13:24 +00002626Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002627 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002628 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002629
Eli Friedman1694e092009-07-18 09:12:15 +00002630 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002631 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002632
Chris Lattner233f7dc2002-08-12 21:17:25 +00002633 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002634 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2635 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002636
2637 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002638 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002639 if (SI->getOpcode() == Instruction::Shl)
2640 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002641 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002642 Context->getConstantExprShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002643
Zhou Sheng843f07672007-04-19 05:39:12 +00002644 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002645 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2646 if (CI->equalsInt(1)) // X * 1 == X
2647 return ReplaceInstUsesWith(I, Op0);
2648 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002649 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002650
Zhou Sheng97b52c22007-03-29 01:57:21 +00002651 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002652 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002653 return BinaryOperator::CreateShl(Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00002654 Context->getConstantInt(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002655 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002656 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002657 if (Op1->isNullValue())
2658 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002659
2660 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2661 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002662 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002663
2664 // As above, vector X*splat(1.0) -> X in all defined cases.
2665 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002666 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2667 if (CI->equalsInt(1))
2668 return ReplaceInstUsesWith(I, Op0);
2669 }
2670 }
Chris Lattnera2881962003-02-18 19:28:33 +00002671 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002672
2673 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2674 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002675 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002676 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002677 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002678 Op1, "tmp");
2679 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00002680 Value *C1C2 = Context->getConstantExprMul(Op1,
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002681 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002682 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002683
2684 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002685
2686 // Try to fold constant mul into select arguments.
2687 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002688 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002689 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002690
2691 if (isa<PHINode>(Op0))
2692 if (Instruction *NV = FoldOpIntoPhi(I))
2693 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002694 }
2695
Owen Andersond672ecb2009-07-03 00:17:18 +00002696 if (Value *Op0v = dyn_castNegVal(Op0, Context)) // -X * -Y = X*Y
2697 if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002698 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002699
Nick Lewycky0c730792008-11-21 07:33:58 +00002700 // (X / Y) * Y = X - (X % Y)
2701 // (X / Y) * -Y = (X % Y) - X
2702 {
2703 Value *Op1 = I.getOperand(1);
2704 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2705 if (!BO ||
2706 (BO->getOpcode() != Instruction::UDiv &&
2707 BO->getOpcode() != Instruction::SDiv)) {
2708 Op1 = Op0;
2709 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2710 }
Owen Andersond672ecb2009-07-03 00:17:18 +00002711 Value *Neg = dyn_castNegVal(Op1, Context);
Nick Lewycky0c730792008-11-21 07:33:58 +00002712 if (BO && BO->hasOneUse() &&
2713 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2714 (BO->getOpcode() == Instruction::UDiv ||
2715 BO->getOpcode() == Instruction::SDiv)) {
2716 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2717
2718 Instruction *Rem;
2719 if (BO->getOpcode() == Instruction::UDiv)
2720 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2721 else
2722 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2723
2724 InsertNewInstBefore(Rem, I);
2725 Rem->takeName(BO);
2726
2727 if (Op1BO == Op1)
2728 return BinaryOperator::CreateSub(Op0BO, Rem);
2729 else
2730 return BinaryOperator::CreateSub(Rem, Op0BO);
2731 }
2732 }
2733
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002734 if (I.getType() == Type::Int1Ty)
2735 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2736
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002737 // If one of the operands of the multiply is a cast from a boolean value, then
2738 // we know the bool is either zero or one, so this is a 'masking' multiply.
2739 // See if we can simplify things based on how the boolean was originally
2740 // formed.
2741 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002742 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002743 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002744 BoolCast = CI;
2745 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002746 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002747 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002748 BoolCast = CI;
2749 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002750 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002751 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2752 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002753 bool TIS = false;
2754
Reid Spencere4d87aa2006-12-23 06:05:41 +00002755 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002756 // multiply into a shift/and combination.
2757 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002758 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2759 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002760 // Shift the X value right to turn it into "all signbits".
Owen Andersond672ecb2009-07-03 00:17:18 +00002761 Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002762 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002763 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002764 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002765 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002766 BoolCast->getOperand(0)->getName()+
2767 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002768
2769 // If the multiply type is not the same as the source type, sign extend
2770 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002771 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002772 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2773 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002774 Instruction::CastOps opcode =
2775 (SrcBits == DstBits ? Instruction::BitCast :
2776 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2777 V = InsertCastBefore(opcode, V, I.getType(), I);
2778 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002779
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002780 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002781 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002782 }
2783 }
2784 }
2785
Chris Lattner7e708292002-06-25 16:13:24 +00002786 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002787}
2788
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002789Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2790 bool Changed = SimplifyCommutative(I);
2791 Value *Op0 = I.getOperand(0);
2792
2793 // Simplify mul instructions with a constant RHS...
2794 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2795 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2796 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2797 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2798 if (Op1F->isExactlyValue(1.0))
2799 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2800 } else if (isa<VectorType>(Op1->getType())) {
2801 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2802 // As above, vector X*splat(1.0) -> X in all defined cases.
2803 if (Constant *Splat = Op1V->getSplatValue()) {
2804 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2805 if (F->isExactlyValue(1.0))
2806 return ReplaceInstUsesWith(I, Op0);
2807 }
2808 }
2809 }
2810
2811 // Try to fold constant mul into select arguments.
2812 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2813 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2814 return R;
2815
2816 if (isa<PHINode>(Op0))
2817 if (Instruction *NV = FoldOpIntoPhi(I))
2818 return NV;
2819 }
2820
Owen Andersond672ecb2009-07-03 00:17:18 +00002821 if (Value *Op0v = dyn_castFNegVal(Op0, Context)) // -X * -Y = X*Y
2822 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002823 return BinaryOperator::CreateFMul(Op0v, Op1v);
2824
2825 return Changed ? &I : 0;
2826}
2827
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002828/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2829/// instruction.
2830bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2831 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2832
2833 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2834 int NonNullOperand = -1;
2835 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2836 if (ST->isNullValue())
2837 NonNullOperand = 2;
2838 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2839 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2840 if (ST->isNullValue())
2841 NonNullOperand = 1;
2842
2843 if (NonNullOperand == -1)
2844 return false;
2845
2846 Value *SelectCond = SI->getOperand(0);
2847
2848 // Change the div/rem to use 'Y' instead of the select.
2849 I.setOperand(1, SI->getOperand(NonNullOperand));
2850
2851 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2852 // problem. However, the select, or the condition of the select may have
2853 // multiple uses. Based on our knowledge that the operand must be non-zero,
2854 // propagate the known value for the select into other uses of it, and
2855 // propagate a known value of the condition into its other users.
2856
2857 // If the select and condition only have a single use, don't bother with this,
2858 // early exit.
2859 if (SI->use_empty() && SelectCond->hasOneUse())
2860 return true;
2861
2862 // Scan the current block backward, looking for other uses of SI.
2863 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2864
2865 while (BBI != BBFront) {
2866 --BBI;
2867 // If we found a call to a function, we can't assume it will return, so
2868 // information from below it cannot be propagated above it.
2869 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2870 break;
2871
2872 // Replace uses of the select or its condition with the known values.
2873 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2874 I != E; ++I) {
2875 if (*I == SI) {
2876 *I = SI->getOperand(NonNullOperand);
2877 AddToWorkList(BBI);
2878 } else if (*I == SelectCond) {
Owen Andersonb3056fa2009-07-21 18:03:38 +00002879 *I = NonNullOperand == 1 ? Context->getTrue() :
2880 Context->getFalse();
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002881 AddToWorkList(BBI);
2882 }
2883 }
2884
2885 // If we past the instruction, quit looking for it.
2886 if (&*BBI == SI)
2887 SI = 0;
2888 if (&*BBI == SelectCond)
2889 SelectCond = 0;
2890
2891 // If we ran out of things to eliminate, break out of the loop.
2892 if (SelectCond == 0 && SI == 0)
2893 break;
2894
2895 }
2896 return true;
2897}
2898
2899
Reid Spencer1628cec2006-10-26 06:15:43 +00002900/// This function implements the transforms on div instructions that work
2901/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2902/// used by the visitors to those instructions.
2903/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002904Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002905 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002906
Chris Lattner50b2ca42008-02-19 06:12:18 +00002907 // undef / X -> 0 for integer.
2908 // undef / X -> undef for FP (the undef could be a snan).
2909 if (isa<UndefValue>(Op0)) {
2910 if (Op0->getType()->isFPOrFPVector())
2911 return ReplaceInstUsesWith(I, Op0);
Owen Andersond672ecb2009-07-03 00:17:18 +00002912 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002913 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002914
2915 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002916 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002917 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002918
Reid Spencer1628cec2006-10-26 06:15:43 +00002919 return 0;
2920}
Misha Brukmanfd939082005-04-21 23:48:37 +00002921
Reid Spencer1628cec2006-10-26 06:15:43 +00002922/// This function implements the transforms common to both integer division
2923/// instructions (udiv and sdiv). It is called by the visitors to those integer
2924/// division instructions.
2925/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002926Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002927 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2928
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002929 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002930 if (Op0 == Op1) {
2931 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002932 Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002933 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00002934 return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002935 }
2936
Owen Andersond672ecb2009-07-03 00:17:18 +00002937 Constant *CI = Context->getConstantInt(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002938 return ReplaceInstUsesWith(I, CI);
2939 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002940
Reid Spencer1628cec2006-10-26 06:15:43 +00002941 if (Instruction *Common = commonDivTransforms(I))
2942 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002943
2944 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2945 // This does not apply for fdiv.
2946 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2947 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002948
2949 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2950 // div X, 1 == X
2951 if (RHS->equalsInt(1))
2952 return ReplaceInstUsesWith(I, Op0);
2953
2954 // (X / C1) / C2 -> X / (C1*C2)
2955 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2956 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2957 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002958 if (MultiplyOverflows(RHS, LHSRHS,
2959 I.getOpcode()==Instruction::SDiv, Context))
2960 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002961 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002962 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002963 Context->getConstantExprMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002964 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002965
Reid Spencerbca0e382007-03-23 20:05:17 +00002966 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002967 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2968 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2969 return R;
2970 if (isa<PHINode>(Op0))
2971 if (Instruction *NV = FoldOpIntoPhi(I))
2972 return NV;
2973 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002974 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002975
Chris Lattnera2881962003-02-18 19:28:33 +00002976 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002977 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002978 if (LHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00002979 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002980
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002981 // It can't be division by zero, hence it must be division by one.
2982 if (I.getType() == Type::Int1Ty)
2983 return ReplaceInstUsesWith(I, Op0);
2984
Nick Lewycky895f0852008-11-27 20:21:08 +00002985 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2986 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2987 // div X, 1 == X
2988 if (X->isOne())
2989 return ReplaceInstUsesWith(I, Op0);
2990 }
2991
Reid Spencer1628cec2006-10-26 06:15:43 +00002992 return 0;
2993}
2994
2995Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2996 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2997
2998 // Handle the integer div common cases
2999 if (Instruction *Common = commonIDivTransforms(I))
3000 return Common;
3001
Reid Spencer1628cec2006-10-26 06:15:43 +00003002 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003003 // X udiv C^2 -> X >> C
3004 // Check to see if this is an unsigned division with an exact power of 2,
3005 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003006 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003007 return BinaryOperator::CreateLShr(Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00003008 Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003009
3010 // X udiv C, where C >= signbit
3011 if (C->getValue().isNegative()) {
Owen Anderson333c4002009-07-09 23:48:35 +00003012 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3013 ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky8ca52482008-11-27 22:41:10 +00003014 I);
Owen Andersond672ecb2009-07-03 00:17:18 +00003015 return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3016 Context->getConstantInt(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003017 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003018 }
3019
3020 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003021 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003022 if (RHSI->getOpcode() == Instruction::Shl &&
3023 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003024 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003025 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003026 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003027 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003028 if (uint32_t C2 = C1.logBase2()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003029 Constant *C2V = Context->getConstantInt(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003030 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003031 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003032 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003033 }
3034 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003035 }
3036
Reid Spencer1628cec2006-10-26 06:15:43 +00003037 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3038 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003039 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003040 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003041 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003042 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003043 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003044 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003045 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003046 // Construct the "on true" case of the select
Owen Andersond672ecb2009-07-03 00:17:18 +00003047 Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003048 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003049 Op0, TC, SI->getName()+".t");
3050 TSI = InsertNewInstBefore(TSI, I);
3051
3052 // Construct the "on false" case of the select
Owen Andersond672ecb2009-07-03 00:17:18 +00003053 Constant *FC = Context->getConstantInt(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003054 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003055 Op0, FC, SI->getName()+".f");
3056 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003057
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003058 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003059 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003060 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003061 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003062 return 0;
3063}
3064
Reid Spencer1628cec2006-10-26 06:15:43 +00003065Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3066 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3067
3068 // Handle the integer div common cases
3069 if (Instruction *Common = commonIDivTransforms(I))
3070 return Common;
3071
3072 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3073 // sdiv X, -1 == -X
3074 if (RHS->isAllOnesValue())
Owen Anderson0a5372e2009-07-13 04:09:18 +00003075 return BinaryOperator::CreateNeg(*Context, Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003076 }
3077
3078 // If the sign bits of both operands are zero (i.e. we can prove they are
3079 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003080 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003081 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003082 if (MaskedValueIsZero(Op0, Mask)) {
3083 if (MaskedValueIsZero(Op1, Mask)) {
3084 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3085 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3086 }
3087 ConstantInt *ShiftedInt;
3088 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value()), *Context) &&
3089 ShiftedInt->getValue().isPowerOf2()) {
3090 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3091 // Safe because the only negative value (1 << Y) can take on is
3092 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3093 // the sign bit set.
3094 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3095 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003096 }
Eli Friedman8be17392009-07-18 09:53:21 +00003097 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003098
3099 return 0;
3100}
3101
3102Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3103 return commonDivTransforms(I);
3104}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003105
Reid Spencer0a783f72006-11-02 01:53:59 +00003106/// This function implements the transforms on rem instructions that work
3107/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3108/// is used by the visitors to those instructions.
3109/// @brief Transforms common to all three rem instructions
3110Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003111 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003112
Chris Lattner50b2ca42008-02-19 06:12:18 +00003113 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3114 if (I.getType()->isFPOrFPVector())
3115 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersond672ecb2009-07-03 00:17:18 +00003116 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003117 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003118 if (isa<UndefValue>(Op1))
3119 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003120
3121 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003122 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3123 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003124
Reid Spencer0a783f72006-11-02 01:53:59 +00003125 return 0;
3126}
3127
3128/// This function implements the transforms common to both integer remainder
3129/// instructions (urem and srem). It is called by the visitors to those integer
3130/// remainder instructions.
3131/// @brief Common integer remainder transforms
3132Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3133 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3134
3135 if (Instruction *common = commonRemTransforms(I))
3136 return common;
3137
Dale Johannesened6af242009-01-21 00:35:19 +00003138 // 0 % X == 0 for integer, we don't need to preserve faults!
3139 if (Constant *LHS = dyn_cast<Constant>(Op0))
3140 if (LHS->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00003141 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003142
Chris Lattner857e8cd2004-12-12 21:48:58 +00003143 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003144 // X % 0 == undef, we don't need to preserve faults!
3145 if (RHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00003146 return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003147
Chris Lattnera2881962003-02-18 19:28:33 +00003148 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003149 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003150
Chris Lattner97943922006-02-28 05:49:21 +00003151 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3152 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3153 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3154 return R;
3155 } else if (isa<PHINode>(Op0I)) {
3156 if (Instruction *NV = FoldOpIntoPhi(I))
3157 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003158 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003159
3160 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003161 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003162 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003163 }
Chris Lattnera2881962003-02-18 19:28:33 +00003164 }
3165
Reid Spencer0a783f72006-11-02 01:53:59 +00003166 return 0;
3167}
3168
3169Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3170 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3171
3172 if (Instruction *common = commonIRemTransforms(I))
3173 return common;
3174
3175 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3176 // X urem C^2 -> X and C
3177 // Check to see if this is an unsigned remainder with an exact power of 2,
3178 // if so, convert to a bitwise and.
3179 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003180 if (C->getValue().isPowerOf2())
Owen Andersond672ecb2009-07-03 00:17:18 +00003181 return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
Reid Spencer0a783f72006-11-02 01:53:59 +00003182 }
3183
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003184 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003185 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3186 if (RHSI->getOpcode() == Instruction::Shl &&
3187 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003188 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Anderson73c6b712009-07-13 20:58:05 +00003189 Constant *N1 = Context->getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003190 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003191 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003192 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003193 }
3194 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003195 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003196
Reid Spencer0a783f72006-11-02 01:53:59 +00003197 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3198 // where C1&C2 are powers of two.
3199 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3200 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3201 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3202 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003203 if ((STO->getValue().isPowerOf2()) &&
3204 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003205 Value *TrueAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003206 BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3207 SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003208 Value *FalseAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003209 BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3210 SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003211 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003212 }
3213 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003214 }
3215
Chris Lattner3f5b8772002-05-06 16:14:14 +00003216 return 0;
3217}
3218
Reid Spencer0a783f72006-11-02 01:53:59 +00003219Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3220 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3221
Dan Gohmancff55092007-11-05 23:16:33 +00003222 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003223 if (Instruction *common = commonIRemTransforms(I))
3224 return common;
3225
Owen Andersond672ecb2009-07-03 00:17:18 +00003226 if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
Nick Lewycky23c04302008-09-03 06:24:21 +00003227 if (!isa<Constant>(RHSNeg) ||
3228 (isa<ConstantInt>(RHSNeg) &&
3229 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003230 // X % -Y -> X % Y
3231 AddUsesToWorkList(I);
3232 I.setOperand(1, RHSNeg);
3233 return &I;
3234 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003235
Dan Gohmancff55092007-11-05 23:16:33 +00003236 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003237 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003238 if (I.getType()->isInteger()) {
3239 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3240 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3241 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003242 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003243 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003244 }
3245
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003246 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003247 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3248 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003249
Nick Lewycky9dce8732008-12-20 16:48:00 +00003250 bool hasNegative = false;
3251 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3252 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3253 if (RHS->getValue().isNegative())
3254 hasNegative = true;
3255
3256 if (hasNegative) {
3257 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003258 for (unsigned i = 0; i != VWidth; ++i) {
3259 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3260 if (RHS->getValue().isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00003261 Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003262 else
3263 Elts[i] = RHS;
3264 }
3265 }
3266
Owen Andersond672ecb2009-07-03 00:17:18 +00003267 Constant *NewRHSV = Context->getConstantVector(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003268 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003269 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003270 I.setOperand(1, NewRHSV);
3271 return &I;
3272 }
3273 }
3274 }
3275
Reid Spencer0a783f72006-11-02 01:53:59 +00003276 return 0;
3277}
3278
3279Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003280 return commonRemTransforms(I);
3281}
3282
Chris Lattner457dd822004-06-09 07:59:58 +00003283// isOneBitSet - Return true if there is exactly one bit set in the specified
3284// constant.
3285static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003286 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003287}
3288
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003289// isHighOnes - Return true if the constant is of the form 1+0+.
3290// This is the same as lowones(~X).
3291static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003292 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003293}
3294
Reid Spencere4d87aa2006-12-23 06:05:41 +00003295/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003296/// are carefully arranged to allow folding of expressions such as:
3297///
3298/// (A < B) | (A > B) --> (A != B)
3299///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003300/// Note that this is only valid if the first and second predicates have the
3301/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003302///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003303/// Three bits are used to represent the condition, as follows:
3304/// 0 A > B
3305/// 1 A == B
3306/// 2 A < B
3307///
3308/// <=> Value Definition
3309/// 000 0 Always false
3310/// 001 1 A > B
3311/// 010 2 A == B
3312/// 011 3 A >= B
3313/// 100 4 A < B
3314/// 101 5 A != B
3315/// 110 6 A <= B
3316/// 111 7 Always true
3317///
3318static unsigned getICmpCode(const ICmpInst *ICI) {
3319 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003320 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003321 case ICmpInst::ICMP_UGT: return 1; // 001
3322 case ICmpInst::ICMP_SGT: return 1; // 001
3323 case ICmpInst::ICMP_EQ: return 2; // 010
3324 case ICmpInst::ICMP_UGE: return 3; // 011
3325 case ICmpInst::ICMP_SGE: return 3; // 011
3326 case ICmpInst::ICMP_ULT: return 4; // 100
3327 case ICmpInst::ICMP_SLT: return 4; // 100
3328 case ICmpInst::ICMP_NE: return 5; // 101
3329 case ICmpInst::ICMP_ULE: return 6; // 110
3330 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003331 // True -> 7
3332 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003333 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003334 return 0;
3335 }
3336}
3337
Evan Cheng8db90722008-10-14 17:15:11 +00003338/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3339/// predicate into a three bit mask. It also returns whether it is an ordered
3340/// predicate by reference.
3341static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3342 isOrdered = false;
3343 switch (CC) {
3344 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3345 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003346 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3347 case FCmpInst::FCMP_UGT: return 1; // 001
3348 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3349 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003350 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3351 case FCmpInst::FCMP_UGE: return 3; // 011
3352 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3353 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003354 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3355 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003356 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3357 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003358 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003359 default:
3360 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003361 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003362 return 0;
3363 }
3364}
3365
Reid Spencere4d87aa2006-12-23 06:05:41 +00003366/// getICmpValue - This is the complement of getICmpCode, which turns an
3367/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003368/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003369/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003370static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003371 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003372 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003373 default: llvm_unreachable("Illegal ICmp code!");
Owen Andersonb3056fa2009-07-21 18:03:38 +00003374 case 0: return Context->getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003375 case 1:
3376 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003377 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003378 else
Owen Anderson333c4002009-07-09 23:48:35 +00003379 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3380 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003381 case 3:
3382 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003383 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003384 else
Owen Anderson333c4002009-07-09 23:48:35 +00003385 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003386 case 4:
3387 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003388 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003389 else
Owen Anderson333c4002009-07-09 23:48:35 +00003390 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3391 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003392 case 6:
3393 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003394 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003395 else
Owen Anderson333c4002009-07-09 23:48:35 +00003396 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
Owen Andersonb3056fa2009-07-21 18:03:38 +00003397 case 7: return Context->getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003398 }
3399}
3400
Evan Cheng8db90722008-10-14 17:15:11 +00003401/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3402/// opcode and two operands into either a FCmp instruction. isordered is passed
3403/// in to determine which kind of predicate to use in the new fcmp instruction.
3404static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003405 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003406 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003407 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003408 case 0:
3409 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003410 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003411 else
Owen Anderson333c4002009-07-09 23:48:35 +00003412 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003413 case 1:
3414 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003415 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003416 else
Owen Anderson333c4002009-07-09 23:48:35 +00003417 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003418 case 2:
3419 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003420 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003421 else
Owen Anderson333c4002009-07-09 23:48:35 +00003422 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003423 case 3:
3424 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003425 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003426 else
Owen Anderson333c4002009-07-09 23:48:35 +00003427 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003428 case 4:
3429 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003430 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003431 else
Owen Anderson333c4002009-07-09 23:48:35 +00003432 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003433 case 5:
3434 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003435 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003436 else
Owen Anderson333c4002009-07-09 23:48:35 +00003437 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003438 case 6:
3439 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003440 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, 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_ULE, LHS, RHS);
Owen Andersonb3056fa2009-07-21 18:03:38 +00003443 case 7: return Context->getTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003444 }
3445}
3446
Chris Lattnerb9553d62008-11-16 04:55:20 +00003447/// PredicatesFoldable - Return true if both predicates match sign or if at
3448/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003449static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3450 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003451 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3452 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003453}
3454
3455namespace {
3456// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3457struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003458 InstCombiner &IC;
3459 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003460 ICmpInst::Predicate pred;
3461 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3462 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3463 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003464 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003465 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3466 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003467 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3468 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003469 return false;
3470 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003471 Instruction *apply(Instruction &Log) const {
3472 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3473 if (ICI->getOperand(0) != LHS) {
3474 assert(ICI->getOperand(1) == LHS);
3475 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003476 }
3477
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003478 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003479 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003480 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003481 unsigned Code;
3482 switch (Log.getOpcode()) {
3483 case Instruction::And: Code = LHSCode & RHSCode; break;
3484 case Instruction::Or: Code = LHSCode | RHSCode; break;
3485 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003486 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003487 }
3488
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003489 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3490 ICmpInst::isSignedPredicate(ICI->getPredicate());
3491
Owen Andersond672ecb2009-07-03 00:17:18 +00003492 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003493 if (Instruction *I = dyn_cast<Instruction>(RV))
3494 return I;
3495 // Otherwise, it's a constant boolean value...
3496 return IC.ReplaceInstUsesWith(Log, RV);
3497 }
3498};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003499} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003500
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003501// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3502// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003503// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003504Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003505 ConstantInt *OpRHS,
3506 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003507 BinaryOperator &TheAnd) {
3508 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003509 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003510 if (!Op->isShift())
Owen Andersond672ecb2009-07-03 00:17:18 +00003511 Together = Context->getConstantExprAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003512
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003513 switch (Op->getOpcode()) {
3514 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003515 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003516 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003517 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003518 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003519 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003520 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003521 }
3522 break;
3523 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003524 if (Together == AndRHS) // (X | C) & C --> C
3525 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003526
Chris Lattner6e7ba452005-01-01 16:22:27 +00003527 if (Op->hasOneUse() && Together != OpRHS) {
3528 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003529 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003530 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003531 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003532 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003533 }
3534 break;
3535 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003536 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003537 // Adding a one to a single bit bit-field should be turned into an XOR
3538 // of the bit. First thing to check is to see if this AND is with a
3539 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003540 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003541
3542 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003543 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003544 // Ok, at this point, we know that we are masking the result of the
3545 // ADD down to exactly one bit. If the constant we are adding has
3546 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003547 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003548
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003549 // Check to see if any bits below the one bit set in AndRHSV are set.
3550 if ((AddRHS & (AndRHSV-1)) == 0) {
3551 // If not, the only thing that can effect the output of the AND is
3552 // the bit specified by AndRHSV. If that bit is set, the effect of
3553 // the XOR is to toggle the bit. If it is clear, then the ADD has
3554 // no effect.
3555 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3556 TheAnd.setOperand(0, X);
3557 return &TheAnd;
3558 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003559 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003560 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003561 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003562 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003563 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003564 }
3565 }
3566 }
3567 }
3568 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003569
3570 case Instruction::Shl: {
3571 // We know that the AND will not produce any of the bits shifted in, so if
3572 // the anded constant includes them, clear them now!
3573 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003574 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003575 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003576 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003577 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003578
Zhou Sheng290bec52007-03-29 08:15:12 +00003579 if (CI->getValue() == ShlMask) {
3580 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003581 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3582 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003583 TheAnd.setOperand(1, CI);
3584 return &TheAnd;
3585 }
3586 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003587 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003588 case Instruction::LShr:
3589 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003590 // We know that the AND will not produce any of the bits shifted in, so if
3591 // the anded constant includes them, clear them now! This only applies to
3592 // unsigned shifts, because a signed shr may bring in set bits!
3593 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003594 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003595 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003596 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003597 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003598
Zhou Sheng290bec52007-03-29 08:15:12 +00003599 if (CI->getValue() == ShrMask) {
3600 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003601 return ReplaceInstUsesWith(TheAnd, Op);
3602 } else if (CI != AndRHS) {
3603 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3604 return &TheAnd;
3605 }
3606 break;
3607 }
3608 case Instruction::AShr:
3609 // Signed shr.
3610 // See if this is shifting in some sign extension, then masking it out
3611 // with an and.
3612 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003613 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003614 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003615 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003616 Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003617 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003618 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003619 // Make the argument unsigned.
3620 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003621 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003622 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003623 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003624 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003625 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003626 }
3627 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003628 }
3629 return 0;
3630}
3631
Chris Lattner8b170942002-08-09 23:47:40 +00003632
Chris Lattnera96879a2004-09-29 17:40:11 +00003633/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3634/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003635/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3636/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003637/// insert new instructions.
3638Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003639 bool isSigned, bool Inside,
3640 Instruction &IB) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003641 assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003642 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003643 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003644
Chris Lattnera96879a2004-09-29 17:40:11 +00003645 if (Inside) {
3646 if (Lo == Hi) // Trivially false.
Owen Anderson333c4002009-07-09 23:48:35 +00003647 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003648
Reid Spencere4d87aa2006-12-23 06:05:41 +00003649 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003650 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003651 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003652 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Owen Anderson333c4002009-07-09 23:48:35 +00003653 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003654 }
3655
3656 // Emit V-Lo <u Hi-Lo
Owen Andersond672ecb2009-07-03 00:17:18 +00003657 Constant *NegLo = Context->getConstantExprNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003658 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003659 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003660 Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003661 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003662 }
3663
3664 if (Lo == Hi) // Trivially true.
Owen Anderson333c4002009-07-09 23:48:35 +00003665 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003666
Reid Spencere4e40032007-03-21 23:19:50 +00003667 // V < Min || V >= Hi -> V > Hi-1
Owen Andersond672ecb2009-07-03 00:17:18 +00003668 Hi = SubOne(cast<ConstantInt>(Hi), Context);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003669 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003670 ICmpInst::Predicate pred = (isSigned ?
3671 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Owen Anderson333c4002009-07-09 23:48:35 +00003672 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003673 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003674
Reid Spencere4e40032007-03-21 23:19:50 +00003675 // Emit V-Lo >u Hi-1-Lo
3676 // Note that Hi has already had one subtracted from it, above.
Owen Andersond672ecb2009-07-03 00:17:18 +00003677 ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003678 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003679 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003680 Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003681 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003682}
3683
Chris Lattner7203e152005-09-18 07:22:02 +00003684// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3685// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3686// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3687// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003688static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003689 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003690 uint32_t BitWidth = Val->getType()->getBitWidth();
3691 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003692
3693 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003694 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003695 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003696 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003697 return true;
3698}
3699
Chris Lattner7203e152005-09-18 07:22:02 +00003700/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3701/// where isSub determines whether the operator is a sub. If we can fold one of
3702/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003703///
3704/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3705/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3706/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3707///
3708/// return (A +/- B).
3709///
3710Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003711 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003712 Instruction &I) {
3713 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3714 if (!LHSI || LHSI->getNumOperands() != 2 ||
3715 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3716
3717 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3718
3719 switch (LHSI->getOpcode()) {
3720 default: return 0;
3721 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00003722 if (Context->getConstantExprAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003723 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003724 if ((Mask->getValue().countLeadingZeros() +
3725 Mask->getValue().countPopulation()) ==
3726 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003727 break;
3728
3729 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3730 // part, we don't need any explicit masks to take them out of A. If that
3731 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003732 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003733 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003734 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003735 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003736 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003737 break;
3738 }
3739 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003740 return 0;
3741 case Instruction::Or:
3742 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003743 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003744 if ((Mask->getValue().countLeadingZeros() +
3745 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersond672ecb2009-07-03 00:17:18 +00003746 && Context->getConstantExprAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003747 break;
3748 return 0;
3749 }
3750
3751 Instruction *New;
3752 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003753 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003754 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003755 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003756 return InsertNewInstBefore(New, I);
3757}
3758
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003759/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3760Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3761 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003762 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003763 ConstantInt *LHSCst, *RHSCst;
3764 ICmpInst::Predicate LHSCC, RHSCC;
3765
Chris Lattnerea065fb2008-11-16 05:10:52 +00003766 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003767 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3768 m_ConstantInt(LHSCst)), *Context) ||
3769 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3770 m_ConstantInt(RHSCst)), *Context))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003771 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003772
3773 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3774 // where C is a power of 2
3775 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3776 LHSCst->getValue().isPowerOf2()) {
3777 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3778 InsertNewInstBefore(NewOr, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003779 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003780 }
3781
3782 // From here on, we only handle:
3783 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3784 if (Val != Val2) return 0;
3785
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003786 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3787 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3788 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3789 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3790 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3791 return 0;
3792
3793 // We can't fold (ugt x, C) & (sgt x, C2).
3794 if (!PredicatesFoldable(LHSCC, RHSCC))
3795 return 0;
3796
3797 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003798 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003799 if (ICmpInst::isSignedPredicate(LHSCC) ||
3800 (ICmpInst::isEquality(LHSCC) &&
3801 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003802 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003803 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003804 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3805
3806 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003807 std::swap(LHS, RHS);
3808 std::swap(LHSCst, RHSCst);
3809 std::swap(LHSCC, RHSCC);
3810 }
3811
3812 // At this point, we know we have have two icmp instructions
3813 // comparing a value against two constants and and'ing the result
3814 // together. Because of the above check, we know that we only have
3815 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3816 // (from the FoldICmpLogical check above), that the two constants
3817 // are not equal and that the larger constant is on the RHS
3818 assert(LHSCst != RHSCst && "Compares not folded above?");
3819
3820 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003821 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003822 case ICmpInst::ICMP_EQ:
3823 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003824 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003825 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3826 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3827 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00003828 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003829 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3830 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3831 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3832 return ReplaceInstUsesWith(I, LHS);
3833 }
3834 case ICmpInst::ICMP_NE:
3835 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003836 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003837 case ICmpInst::ICMP_ULT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003838 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003839 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003840 break; // (X != 13 & X u< 15) -> no change
3841 case ICmpInst::ICMP_SLT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003842 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003843 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003844 break; // (X != 13 & X s< 15) -> no change
3845 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3846 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3847 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3848 return ReplaceInstUsesWith(I, RHS);
3849 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003850 if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3851 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003852 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3853 Val->getName()+".off");
3854 InsertNewInstBefore(Add, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003855 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
Owen Andersond672ecb2009-07-03 00:17:18 +00003856 Context->getConstantInt(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003857 }
3858 break; // (X != 13 & X != 15) -> no change
3859 }
3860 break;
3861 case ICmpInst::ICMP_ULT:
3862 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003863 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003864 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3865 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00003866 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003867 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3868 break;
3869 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3870 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3871 return ReplaceInstUsesWith(I, LHS);
3872 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3873 break;
3874 }
3875 break;
3876 case ICmpInst::ICMP_SLT:
3877 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003878 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003879 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3880 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00003881 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003882 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3883 break;
3884 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3885 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3886 return ReplaceInstUsesWith(I, LHS);
3887 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3888 break;
3889 }
3890 break;
3891 case ICmpInst::ICMP_UGT:
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) -> X == 15
3895 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3896 return ReplaceInstUsesWith(I, RHS);
3897 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3898 break;
3899 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003900 if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003901 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003902 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003903 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003904 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3905 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003906 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3907 break;
3908 }
3909 break;
3910 case ICmpInst::ICMP_SGT:
3911 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003912 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003913 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3914 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3915 return ReplaceInstUsesWith(I, RHS);
3916 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3917 break;
3918 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003919 if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003920 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003921 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003922 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003923 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3924 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003925 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3926 break;
3927 }
3928 break;
3929 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003930
3931 return 0;
3932}
3933
3934
Chris Lattner7e708292002-06-25 16:13:24 +00003935Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003936 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003937 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003938
Chris Lattnere87597f2004-10-16 18:11:37 +00003939 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003940 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003941
Chris Lattner6e7ba452005-01-01 16:22:27 +00003942 // and X, X = X
3943 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003944 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003945
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003946 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003947 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00003948 if (SimplifyDemandedInstructionBits(I))
3949 return &I;
3950 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003951 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003952 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003953 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003954 } else if (isa<ConstantAggregateZero>(Op1)) {
3955 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003956 }
3957 }
Dan Gohman6de29f82009-06-15 22:12:54 +00003958
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003959 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003960 const APInt& AndRHSMask = AndRHS->getValue();
3961 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003962
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003963 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003964 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003965 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003966 Value *Op0LHS = Op0I->getOperand(0);
3967 Value *Op0RHS = Op0I->getOperand(1);
3968 switch (Op0I->getOpcode()) {
3969 case Instruction::Xor:
3970 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003971 // If the mask is only needed on one incoming arm, push it up.
3972 if (Op0I->hasOneUse()) {
3973 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3974 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003975 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003976 Op0RHS->getName()+".masked");
3977 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003978 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003979 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003980 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003981 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003982 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3983 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003984 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003985 Op0LHS->getName()+".masked");
3986 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003987 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003988 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3989 }
3990 }
3991
Chris Lattner6e7ba452005-01-01 16:22:27 +00003992 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003993 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003994 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3995 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3996 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3997 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003998 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003999 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004000 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004001 break;
4002
4003 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004004 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4005 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4006 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4007 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004008 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004009
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004010 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4011 // has 1's for all bits that the subtraction with A might affect.
4012 if (Op0I->hasOneUse()) {
4013 uint32_t BitWidth = AndRHSMask.getBitWidth();
4014 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4015 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4016
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004017 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004018 if (!(A && A->isZero()) && // avoid infinite recursion.
4019 MaskedValueIsZero(Op0LHS, Mask)) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00004020 Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004021 InsertNewInstBefore(NewNeg, I);
4022 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4023 }
4024 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004025 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004026
4027 case Instruction::Shl:
4028 case Instruction::LShr:
4029 // (1 << x) & 1 --> zext(x == 0)
4030 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004031 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Owen Anderson333c4002009-07-09 23:48:35 +00004032 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4033 Op0RHS, Context->getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004034 InsertNewInstBefore(NewICmp, I);
4035 return new ZExtInst(NewICmp, I.getType());
4036 }
4037 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004038 }
4039
Chris Lattner58403262003-07-23 19:25:52 +00004040 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004041 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004042 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004043 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004044 // If this is an integer truncation or change from signed-to-unsigned, and
4045 // if the source is an and/or with immediate, transform it. This
4046 // frequently occurs for bitfield accesses.
4047 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004048 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004049 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004050 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004051 if (CastOp->getOpcode() == Instruction::And) {
4052 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004053 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4054 // This will fold the two constants together, which may allow
4055 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004056 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004057 CastOp->getOperand(0), I.getType(),
4058 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004059 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004060 // trunc_or_bitcast(C1)&C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004061 Constant *C3 =
4062 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4063 C3 = Context->getConstantExprAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004064 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004065 } else if (CastOp->getOpcode() == Instruction::Or) {
4066 // Change: and (cast (or X, C1) to T), C2
4067 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004068 Constant *C3 =
4069 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4070 if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4071 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004072 return ReplaceInstUsesWith(I, AndRHS);
4073 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004074 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004075 }
Chris Lattner06782f82003-07-23 19:36:21 +00004076 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004077
4078 // Try to fold constant and into select arguments.
4079 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004080 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004081 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004082 if (isa<PHINode>(Op0))
4083 if (Instruction *NV = FoldOpIntoPhi(I))
4084 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004085 }
4086
Owen Andersond672ecb2009-07-03 00:17:18 +00004087 Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4088 Value *Op1NotVal = dyn_castNotVal(Op1, Context);
Chris Lattnera2881962003-02-18 19:28:33 +00004089
Chris Lattner5b62aa72004-06-18 06:07:51 +00004090 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00004091 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004092
Misha Brukmancb6267b2004-07-30 12:50:08 +00004093 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004094 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004095 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004096 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004097 InsertNewInstBefore(Or, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004098 return BinaryOperator::CreateNot(*Context, Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004099 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004100
4101 {
Chris Lattner003b6202007-06-15 05:58:24 +00004102 Value *A = 0, *B = 0, *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004103 if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004104 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4105 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004106
4107 // (A|B) & ~(A&B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004108 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004109 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004110 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004111 }
4112 }
4113
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004114 if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004115 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4116 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004117
4118 // ~(A&B) & (A|B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004119 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004120 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004121 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004122 }
4123 }
Chris Lattner64daab52006-04-01 08:03:55 +00004124
4125 if (Op0->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004126 match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004127 if (A == Op1) { // (A^B)&A -> A&(A^B)
4128 I.swapOperands(); // Simplify below
4129 std::swap(Op0, Op1);
4130 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4131 cast<BinaryOperator>(Op0)->swapOperands();
4132 I.swapOperands(); // Simplify below
4133 std::swap(Op0, Op1);
4134 }
4135 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004136
Chris Lattner64daab52006-04-01 08:03:55 +00004137 if (Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004138 match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004139 if (B == Op0) { // B&(A^B) -> B&(B^A)
4140 cast<BinaryOperator>(Op1)->swapOperands();
4141 std::swap(A, B);
4142 }
4143 if (A == Op0) { // A&(A^B) -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00004144 Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004145 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004146 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004147 }
4148 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004149
4150 // (A&((~A)|B)) -> A&B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004151 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4152 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004153 return BinaryOperator::CreateAnd(A, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004154 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4155 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004156 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004157 }
4158
Reid Spencere4d87aa2006-12-23 06:05:41 +00004159 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4160 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004161 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004162 return R;
4163
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004164 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4165 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4166 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004167 }
4168
Chris Lattner6fc205f2006-05-05 06:39:07 +00004169 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004170 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4171 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4172 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4173 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004174 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004175 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004176 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4177 I.getType(), TD) &&
4178 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4179 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004180 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004181 Op1C->getOperand(0),
4182 I.getName());
4183 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004184 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004185 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004186 }
Chris Lattnere511b742006-11-14 07:46:50 +00004187
4188 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004189 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4190 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4191 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004192 SI0->getOperand(1) == SI1->getOperand(1) &&
4193 (SI0->hasOneUse() || SI1->hasOneUse())) {
4194 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004195 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004196 SI1->getOperand(0),
4197 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004198 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004199 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004200 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004201 }
4202
Evan Cheng8db90722008-10-14 17:15:11 +00004203 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004204 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4205 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4206 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng8db90722008-10-14 17:15:11 +00004207 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4208 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner99c65742007-10-24 05:38:08 +00004209 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4210 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4211 // If either of the constants are nans, then the whole thing returns
4212 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004213 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersonb3056fa2009-07-21 18:03:38 +00004214 return ReplaceInstUsesWith(I, Context->getFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00004215 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
4216 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner99c65742007-10-24 05:38:08 +00004217 }
Evan Cheng8db90722008-10-14 17:15:11 +00004218 } else {
4219 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4220 FCmpInst::Predicate Op0CC, Op1CC;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004221 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4222 m_Value(Op0RHS)), *Context) &&
4223 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4224 m_Value(Op1RHS)), *Context)) {
Evan Cheng4990b252008-10-14 18:13:38 +00004225 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4226 // Swap RHS operands to match LHS.
4227 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4228 std::swap(Op1LHS, Op1RHS);
4229 }
Evan Cheng8db90722008-10-14 17:15:11 +00004230 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4231 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4232 if (Op0CC == Op1CC)
Owen Anderson333c4002009-07-09 23:48:35 +00004233 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4234 Op0LHS, Op0RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00004235 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4236 Op1CC == FCmpInst::FCMP_FALSE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00004237 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng8db90722008-10-14 17:15:11 +00004238 else if (Op0CC == FCmpInst::FCMP_TRUE)
4239 return ReplaceInstUsesWith(I, Op1);
4240 else if (Op1CC == FCmpInst::FCMP_TRUE)
4241 return ReplaceInstUsesWith(I, Op0);
4242 bool Op0Ordered;
4243 bool Op1Ordered;
4244 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4245 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4246 if (Op1Pred == 0) {
4247 std::swap(Op0, Op1);
4248 std::swap(Op0Pred, Op1Pred);
4249 std::swap(Op0Ordered, Op1Ordered);
4250 }
4251 if (Op0Pred == 0) {
4252 // uno && ueq -> uno && (uno || eq) -> ueq
4253 // ord && olt -> ord && (ord && lt) -> olt
4254 if (Op0Ordered == Op1Ordered)
4255 return ReplaceInstUsesWith(I, Op1);
4256 // uno && oeq -> uno && (ord && eq) -> false
4257 // uno && ord -> false
4258 if (!Op0Ordered)
Owen Andersonb3056fa2009-07-21 18:03:38 +00004259 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng8db90722008-10-14 17:15:11 +00004260 // ord && ueq -> ord && (uno || eq) -> oeq
4261 return cast<Instruction>(getFCmpValue(true, Op1Pred,
Owen Andersond672ecb2009-07-03 00:17:18 +00004262 Op0LHS, Op0RHS, Context));
Evan Cheng8db90722008-10-14 17:15:11 +00004263 }
4264 }
4265 }
4266 }
Chris Lattner99c65742007-10-24 05:38:08 +00004267 }
4268 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004269
Chris Lattner7e708292002-06-25 16:13:24 +00004270 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004271}
4272
Chris Lattner8c34cd22008-10-05 02:13:19 +00004273/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4274/// capable of providing pieces of a bswap. The subexpression provides pieces
4275/// of a bswap if it is proven that each of the non-zero bytes in the output of
4276/// the expression came from the corresponding "byte swapped" byte in some other
4277/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4278/// we know that the expression deposits the low byte of %X into the high byte
4279/// of the bswap result and that all other bytes are zero. This expression is
4280/// accepted, the high byte of ByteValues is set to X to indicate a correct
4281/// match.
4282///
4283/// This function returns true if the match was unsuccessful and false if so.
4284/// On entry to the function the "OverallLeftShift" is a signed integer value
4285/// indicating the number of bytes that the subexpression is later shifted. For
4286/// example, if the expression is later right shifted by 16 bits, the
4287/// OverallLeftShift value would be -2 on entry. This is used to specify which
4288/// byte of ByteValues is actually being set.
4289///
4290/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4291/// byte is masked to zero by a user. For example, in (X & 255), X will be
4292/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4293/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4294/// always in the local (OverallLeftShift) coordinate space.
4295///
4296static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4297 SmallVector<Value*, 8> &ByteValues) {
4298 if (Instruction *I = dyn_cast<Instruction>(V)) {
4299 // If this is an or instruction, it may be an inner node of the bswap.
4300 if (I->getOpcode() == Instruction::Or) {
4301 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4302 ByteValues) ||
4303 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4304 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004305 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004306
4307 // If this is a logical shift by a constant multiple of 8, recurse with
4308 // OverallLeftShift and ByteMask adjusted.
4309 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4310 unsigned ShAmt =
4311 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4312 // Ensure the shift amount is defined and of a byte value.
4313 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4314 return true;
4315
4316 unsigned ByteShift = ShAmt >> 3;
4317 if (I->getOpcode() == Instruction::Shl) {
4318 // X << 2 -> collect(X, +2)
4319 OverallLeftShift += ByteShift;
4320 ByteMask >>= ByteShift;
4321 } else {
4322 // X >>u 2 -> collect(X, -2)
4323 OverallLeftShift -= ByteShift;
4324 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004325 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004326 }
4327
4328 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4329 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4330
4331 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4332 ByteValues);
4333 }
4334
4335 // If this is a logical 'and' with a mask that clears bytes, clear the
4336 // corresponding bytes in ByteMask.
4337 if (I->getOpcode() == Instruction::And &&
4338 isa<ConstantInt>(I->getOperand(1))) {
4339 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4340 unsigned NumBytes = ByteValues.size();
4341 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4342 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4343
4344 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4345 // If this byte is masked out by a later operation, we don't care what
4346 // the and mask is.
4347 if ((ByteMask & (1 << i)) == 0)
4348 continue;
4349
4350 // If the AndMask is all zeros for this byte, clear the bit.
4351 APInt MaskB = AndMask & Byte;
4352 if (MaskB == 0) {
4353 ByteMask &= ~(1U << i);
4354 continue;
4355 }
4356
4357 // If the AndMask is not all ones for this byte, it's not a bytezap.
4358 if (MaskB != Byte)
4359 return true;
4360
4361 // Otherwise, this byte is kept.
4362 }
4363
4364 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4365 ByteValues);
4366 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004367 }
4368
Chris Lattner8c34cd22008-10-05 02:13:19 +00004369 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4370 // the input value to the bswap. Some observations: 1) if more than one byte
4371 // is demanded from this input, then it could not be successfully assembled
4372 // into a byteswap. At least one of the two bytes would not be aligned with
4373 // their ultimate destination.
4374 if (!isPowerOf2_32(ByteMask)) return true;
4375 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004376
Chris Lattner8c34cd22008-10-05 02:13:19 +00004377 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4378 // is demanded, it needs to go into byte 0 of the result. This means that the
4379 // byte needs to be shifted until it lands in the right byte bucket. The
4380 // shift amount depends on the position: if the byte is coming from the high
4381 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4382 // low part, it must be shifted left.
4383 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4384 if (InputByteNo < ByteValues.size()/2) {
4385 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4386 return true;
4387 } else {
4388 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4389 return true;
4390 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004391
4392 // If the destination byte value is already defined, the values are or'd
4393 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004394 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004395 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004396 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004397 return false;
4398}
4399
4400/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4401/// If so, insert the new bswap intrinsic and return it.
4402Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004403 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004404 if (!ITy || ITy->getBitWidth() % 16 ||
4405 // ByteMask only allows up to 32-byte values.
4406 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004407 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004408
4409 /// ByteValues - For each byte of the result, we keep track of which value
4410 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004411 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004412 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004413
4414 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004415 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4416 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004417 return 0;
4418
4419 // Check to see if all of the bytes come from the same value.
4420 Value *V = ByteValues[0];
4421 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4422
4423 // Check to make sure that all of the bytes come from the same value.
4424 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4425 if (ByteValues[i] != V)
4426 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004427 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004428 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004429 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004430 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004431}
4432
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004433/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4434/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4435/// we can simplify this expression to "cond ? C : D or B".
4436static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004437 Value *C, Value *D,
4438 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004439 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004440 Value *Cond = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004441 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004442 return 0;
4443
Chris Lattnera6a474d2008-11-16 04:26:55 +00004444 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004445 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004446 return SelectInst::Create(Cond, C, B);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004447 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004448 return SelectInst::Create(Cond, C, B);
4449 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004450 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004451 return SelectInst::Create(Cond, C, D);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004452 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004453 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004454 return 0;
4455}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004456
Chris Lattner69d4ced2008-11-16 05:20:07 +00004457/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4458Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4459 ICmpInst *LHS, ICmpInst *RHS) {
4460 Value *Val, *Val2;
4461 ConstantInt *LHSCst, *RHSCst;
4462 ICmpInst::Predicate LHSCC, RHSCC;
4463
4464 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004465 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4466 m_ConstantInt(LHSCst)), *Context) ||
4467 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4468 m_ConstantInt(RHSCst)), *Context))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004469 return 0;
4470
4471 // From here on, we only handle:
4472 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4473 if (Val != Val2) return 0;
4474
4475 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4476 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4477 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4478 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4479 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4480 return 0;
4481
4482 // We can't fold (ugt x, C) | (sgt x, C2).
4483 if (!PredicatesFoldable(LHSCC, RHSCC))
4484 return 0;
4485
4486 // Ensure that the larger constant is on the RHS.
4487 bool ShouldSwap;
4488 if (ICmpInst::isSignedPredicate(LHSCC) ||
4489 (ICmpInst::isEquality(LHSCC) &&
4490 ICmpInst::isSignedPredicate(RHSCC)))
4491 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4492 else
4493 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4494
4495 if (ShouldSwap) {
4496 std::swap(LHS, RHS);
4497 std::swap(LHSCst, RHSCst);
4498 std::swap(LHSCC, RHSCC);
4499 }
4500
4501 // At this point, we know we have have two icmp instructions
4502 // comparing a value against two constants and or'ing the result
4503 // together. Because of the above check, we know that we only have
4504 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4505 // FoldICmpLogical check above), that the two constants are not
4506 // equal.
4507 assert(LHSCst != RHSCst && "Compares not folded above?");
4508
4509 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004510 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004511 case ICmpInst::ICMP_EQ:
4512 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004513 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004514 case ICmpInst::ICMP_EQ:
Owen Andersond672ecb2009-07-03 00:17:18 +00004515 if (LHSCst == SubOne(RHSCst, Context)) {
4516 // (X == 13 | X == 14) -> X-13 <u 2
4517 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004518 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4519 Val->getName()+".off");
4520 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00004521 AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
Owen Anderson333c4002009-07-09 23:48:35 +00004522 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004523 }
4524 break; // (X == 13 | X == 15) -> no change
4525 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4526 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4527 break;
4528 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4529 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4530 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4531 return ReplaceInstUsesWith(I, RHS);
4532 }
4533 break;
4534 case ICmpInst::ICMP_NE:
4535 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004536 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004537 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4538 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4539 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4540 return ReplaceInstUsesWith(I, LHS);
4541 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4542 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4543 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00004544 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004545 }
4546 break;
4547 case ICmpInst::ICMP_ULT:
4548 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004549 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004550 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4551 break;
4552 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4553 // If RHSCst is [us]MAXINT, it is always false. Not handling
4554 // this can cause overflow.
4555 if (RHSCst->isMaxValue(false))
4556 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004557 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4558 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004559 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4560 break;
4561 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4562 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4563 return ReplaceInstUsesWith(I, RHS);
4564 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4565 break;
4566 }
4567 break;
4568 case ICmpInst::ICMP_SLT:
4569 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004570 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004571 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4572 break;
4573 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4574 // If RHSCst is [us]MAXINT, it is always false. Not handling
4575 // this can cause overflow.
4576 if (RHSCst->isMaxValue(true))
4577 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004578 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4579 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004580 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4581 break;
4582 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4583 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4584 return ReplaceInstUsesWith(I, RHS);
4585 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4586 break;
4587 }
4588 break;
4589 case ICmpInst::ICMP_UGT:
4590 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004591 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004592 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4593 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4594 return ReplaceInstUsesWith(I, LHS);
4595 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4596 break;
4597 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4598 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00004599 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004600 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4601 break;
4602 }
4603 break;
4604 case ICmpInst::ICMP_SGT:
4605 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004606 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004607 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4608 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4609 return ReplaceInstUsesWith(I, LHS);
4610 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4611 break;
4612 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4613 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00004614 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004615 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4616 break;
4617 }
4618 break;
4619 }
4620 return 0;
4621}
4622
Bill Wendlinga698a472008-12-01 08:23:25 +00004623/// FoldOrWithConstants - This helper function folds:
4624///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004625/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004626///
4627/// into:
4628///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004629/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004630///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004631/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004632Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004633 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004634 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4635 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004636
Bill Wendling286a0542008-12-02 06:24:20 +00004637 Value *V1 = 0;
4638 ConstantInt *CI2 = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004639 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004640
Bill Wendling29976b92008-12-02 06:18:11 +00004641 APInt Xor = CI1->getValue() ^ CI2->getValue();
4642 if (!Xor.isAllOnesValue()) return 0;
4643
Bill Wendling286a0542008-12-02 06:24:20 +00004644 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004645 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004646 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4647 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004648 }
4649
4650 return 0;
4651}
4652
Chris Lattner7e708292002-06-25 16:13:24 +00004653Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004654 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004655 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004656
Chris Lattner42593e62007-03-24 23:56:43 +00004657 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004658 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004659
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004660 // or X, X = X
4661 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004662 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004663
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004664 // See if we can simplify any instructions used by the instruction whose sole
4665 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004666 if (SimplifyDemandedInstructionBits(I))
4667 return &I;
4668 if (isa<VectorType>(I.getType())) {
4669 if (isa<ConstantAggregateZero>(Op1)) {
4670 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4671 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4672 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4673 return ReplaceInstUsesWith(I, I.getOperand(1));
4674 }
Chris Lattner42593e62007-03-24 23:56:43 +00004675 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004676
Chris Lattner3f5b8772002-05-06 16:14:14 +00004677 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004678 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004679 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004680 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004681 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) &&
4682 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004683 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004684 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004685 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004686 return BinaryOperator::CreateAnd(Or,
Owen Andersond672ecb2009-07-03 00:17:18 +00004687 Context->getConstantInt(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004688 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004689
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004690 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004691 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) &&
4692 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004693 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004694 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004695 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004696 return BinaryOperator::CreateXor(Or,
Owen Andersond672ecb2009-07-03 00:17:18 +00004697 Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004698 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004699
4700 // Try to fold constant and into select arguments.
4701 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004702 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004703 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004704 if (isa<PHINode>(Op0))
4705 if (Instruction *NV = FoldOpIntoPhi(I))
4706 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004707 }
4708
Chris Lattner4f637d42006-01-06 17:59:59 +00004709 Value *A = 0, *B = 0;
4710 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004711
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004712 if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004713 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4714 return ReplaceInstUsesWith(I, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004715 if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004716 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4717 return ReplaceInstUsesWith(I, Op0);
4718
Chris Lattner6423d4c2006-07-10 20:25:24 +00004719 // (A | B) | C and A | (B | C) -> bswap if possible.
4720 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004721 if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4722 match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4723 (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4724 match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004725 if (Instruction *BSwap = MatchBSwap(I))
4726 return BSwap;
4727 }
4728
Chris Lattner6e4c6492005-05-09 04:58:36 +00004729 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004730 if (Op0->hasOneUse() &&
4731 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004732 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004733 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004734 InsertNewInstBefore(NOr, I);
4735 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004736 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004737 }
4738
4739 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004740 if (Op1->hasOneUse() &&
4741 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004742 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004743 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004744 InsertNewInstBefore(NOr, I);
4745 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004746 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004747 }
4748
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004749 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004750 Value *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004751 if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4752 match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004753 Value *V1 = 0, *V2 = 0, *V3 = 0;
4754 C1 = dyn_cast<ConstantInt>(C);
4755 C2 = dyn_cast<ConstantInt>(D);
4756 if (C1 && C2) { // (A & C1)|(B & C2)
4757 // If we have: ((V + N) & C1) | (V & C2)
4758 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4759 // replace with V+N.
4760 if (C1->getValue() == ~C2->getValue()) {
4761 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004762 match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004763 // Add commutes, try both ways.
4764 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4765 return ReplaceInstUsesWith(I, A);
4766 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4767 return ReplaceInstUsesWith(I, A);
4768 }
4769 // Or commutes, try both ways.
4770 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004771 match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004772 // Add commutes, try both ways.
4773 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4774 return ReplaceInstUsesWith(I, B);
4775 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4776 return ReplaceInstUsesWith(I, B);
4777 }
4778 }
Chris Lattner044e5332007-04-08 08:01:49 +00004779 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004780 }
4781
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004782 // Check to see if we have any common things being and'ed. If so, find the
4783 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004784 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4785 if (A == B) // (A & C)|(A & D) == A & (C|D)
4786 V1 = A, V2 = C, V3 = D;
4787 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4788 V1 = A, V2 = B, V3 = C;
4789 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4790 V1 = C, V2 = A, V3 = D;
4791 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4792 V1 = C, V2 = A, V3 = B;
4793
4794 if (V1) {
4795 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004796 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4797 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004798 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004799 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004800
Dan Gohman1975d032008-10-30 20:40:10 +00004801 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004802 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004803 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004804 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004805 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004806 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004807 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004808 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004809 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004810
Bill Wendlingb01865c2008-11-30 13:52:49 +00004811 // ((A&~B)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004812 if ((match(C, m_Not(m_Specific(D)), *Context) &&
4813 match(B, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004814 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004815 // ((~B&A)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004816 if ((match(A, m_Not(m_Specific(D)), *Context) &&
4817 match(B, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004818 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004819 // ((A&~B)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004820 if ((match(C, m_Not(m_Specific(B)), *Context) &&
4821 match(D, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004822 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004823 // ((~B&A)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004824 if ((match(A, m_Not(m_Specific(B)), *Context) &&
4825 match(D, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004826 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004827 }
Chris Lattnere511b742006-11-14 07:46:50 +00004828
4829 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004830 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4831 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4832 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004833 SI0->getOperand(1) == SI1->getOperand(1) &&
4834 (SI0->hasOneUse() || SI1->hasOneUse())) {
4835 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004836 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004837 SI1->getOperand(0),
4838 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004839 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004840 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004841 }
4842 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004843
Bill Wendlingb3833d12008-12-01 01:07:11 +00004844 // ((A|B)&1)|(B&-2) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004845 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4846 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004847 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004848 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004849 }
4850 // (B&-2)|((A|B)&1) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004851 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4852 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004853 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004854 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004855 }
4856
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004857 if (match(Op0, m_Not(m_Value(A)), *Context)) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004858 if (A == Op1) // ~A | A == -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004859 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004860 } else {
4861 A = 0;
4862 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004863 // Note, A is still live here!
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004864 if (match(Op1, m_Not(m_Value(B)), *Context)) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004865 if (Op0 == B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004866 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004867
Misha Brukmancb6267b2004-07-30 12:50:08 +00004868 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004869 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004870 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004871 I.getName()+".demorgan"), I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004872 return BinaryOperator::CreateNot(*Context, And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004873 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004874 }
Chris Lattnera2881962003-02-18 19:28:33 +00004875
Reid Spencere4d87aa2006-12-23 06:05:41 +00004876 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4877 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004878 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004879 return R;
4880
Chris Lattner69d4ced2008-11-16 05:20:07 +00004881 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4882 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4883 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004884 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004885
4886 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004887 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004888 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004889 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004890 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4891 !isa<ICmpInst>(Op1C->getOperand(0))) {
4892 const Type *SrcTy = Op0C->getOperand(0)->getType();
4893 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4894 // Only do this if the casts both really cause code to be
4895 // generated.
4896 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4897 I.getType(), TD) &&
4898 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4899 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004900 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004901 Op1C->getOperand(0),
4902 I.getName());
4903 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004904 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004905 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004906 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004907 }
Chris Lattner99c65742007-10-24 05:38:08 +00004908 }
4909
4910
4911 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4912 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4913 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4914 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004915 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004916 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004917 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4918 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4919 // If either of the constants are nans, then the whole thing returns
4920 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004921 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersonb3056fa2009-07-21 18:03:38 +00004922 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner99c65742007-10-24 05:38:08 +00004923
4924 // Otherwise, no need to compare the two constants, compare the
4925 // rest.
Owen Anderson333c4002009-07-09 23:48:35 +00004926 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4927 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner99c65742007-10-24 05:38:08 +00004928 }
Evan Cheng40300622008-10-14 18:44:08 +00004929 } else {
4930 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4931 FCmpInst::Predicate Op0CC, Op1CC;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004932 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4933 m_Value(Op0RHS)), *Context) &&
4934 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4935 m_Value(Op1RHS)), *Context)) {
Evan Cheng40300622008-10-14 18:44:08 +00004936 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4937 // Swap RHS operands to match LHS.
4938 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4939 std::swap(Op1LHS, Op1RHS);
4940 }
4941 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4942 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4943 if (Op0CC == Op1CC)
Owen Anderson333c4002009-07-09 23:48:35 +00004944 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4945 Op0LHS, Op0RHS);
Evan Cheng40300622008-10-14 18:44:08 +00004946 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4947 Op1CC == FCmpInst::FCMP_TRUE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00004948 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng40300622008-10-14 18:44:08 +00004949 else if (Op0CC == FCmpInst::FCMP_FALSE)
4950 return ReplaceInstUsesWith(I, Op1);
4951 else if (Op1CC == FCmpInst::FCMP_FALSE)
4952 return ReplaceInstUsesWith(I, Op0);
4953 bool Op0Ordered;
4954 bool Op1Ordered;
4955 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4956 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4957 if (Op0Ordered == Op1Ordered) {
4958 // If both are ordered or unordered, return a new fcmp with
4959 // or'ed predicates.
4960 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
Owen Andersond672ecb2009-07-03 00:17:18 +00004961 Op0LHS, Op0RHS, Context);
Evan Cheng40300622008-10-14 18:44:08 +00004962 if (Instruction *I = dyn_cast<Instruction>(RV))
4963 return I;
4964 // Otherwise, it's a constant boolean value...
4965 return ReplaceInstUsesWith(I, RV);
4966 }
4967 }
4968 }
4969 }
Chris Lattner99c65742007-10-24 05:38:08 +00004970 }
4971 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004972
Chris Lattner7e708292002-06-25 16:13:24 +00004973 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004974}
4975
Dan Gohman844731a2008-05-13 00:00:25 +00004976namespace {
4977
Chris Lattnerc317d392004-02-16 01:20:27 +00004978// XorSelf - Implements: X ^ X --> 0
4979struct XorSelf {
4980 Value *RHS;
4981 XorSelf(Value *rhs) : RHS(rhs) {}
4982 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4983 Instruction *apply(BinaryOperator &Xor) const {
4984 return &Xor;
4985 }
4986};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004987
Dan Gohman844731a2008-05-13 00:00:25 +00004988}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004989
Chris Lattner7e708292002-06-25 16:13:24 +00004990Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004991 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004992 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004993
Evan Chengd34af782008-03-25 20:07:13 +00004994 if (isa<UndefValue>(Op1)) {
4995 if (isa<UndefValue>(Op0))
4996 // Handle undef ^ undef -> 0 special case. This is a common
4997 // idiom (misuse).
Owen Andersond672ecb2009-07-03 00:17:18 +00004998 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004999 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005000 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005001
Chris Lattnerc317d392004-02-16 01:20:27 +00005002 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Owen Andersond672ecb2009-07-03 00:17:18 +00005003 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005004 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersond672ecb2009-07-03 00:17:18 +00005005 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005006 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005007
5008 // See if we can simplify any instructions used by the instruction whose sole
5009 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005010 if (SimplifyDemandedInstructionBits(I))
5011 return &I;
5012 if (isa<VectorType>(I.getType()))
5013 if (isa<ConstantAggregateZero>(Op1))
5014 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005015
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005016 // Is this a ~ operation?
Owen Andersond672ecb2009-07-03 00:17:18 +00005017 if (Value *NotOp = dyn_castNotVal(&I, Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005018 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5019 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5020 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5021 if (Op0I->getOpcode() == Instruction::And ||
5022 Op0I->getOpcode() == Instruction::Or) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005023 if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5024 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005025 Instruction *NotY =
Owen Anderson73c6b712009-07-13 20:58:05 +00005026 BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005027 Op0I->getOperand(1)->getName()+".not");
5028 InsertNewInstBefore(NotY, I);
5029 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005030 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005031 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005032 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005033 }
5034 }
5035 }
5036 }
5037
5038
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005039 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Andersonb3056fa2009-07-21 18:03:38 +00005040 if (RHS == Context->getTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005041 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005042 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005043 return new ICmpInst(*Context, ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005044 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005045
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005046 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005047 return new FCmpInst(*Context, FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005048 FCI->getOperand(0), FCI->getOperand(1));
5049 }
5050
Nick Lewycky517e1f52008-05-31 19:01:33 +00005051 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5052 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5053 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5054 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5055 Instruction::CastOps Opcode = Op0C->getOpcode();
5056 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005057 if (RHS == Context->getConstantExprCast(Opcode,
Owen Andersonb3056fa2009-07-21 18:03:38 +00005058 Context->getTrue(),
Nick Lewycky517e1f52008-05-31 19:01:33 +00005059 Op0C->getDestTy())) {
5060 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
Owen Anderson333c4002009-07-09 23:48:35 +00005061 *Context,
Nick Lewycky517e1f52008-05-31 19:01:33 +00005062 CI->getOpcode(), CI->getInversePredicate(),
5063 CI->getOperand(0), CI->getOperand(1)), I);
5064 NewCI->takeName(CI);
5065 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5066 }
5067 }
5068 }
5069 }
5070 }
5071
Reid Spencere4d87aa2006-12-23 06:05:41 +00005072 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005073 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005074 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5075 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005076 Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5077 Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5078 Context->getConstantInt(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005079 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005080 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005081
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005082 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005083 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005084 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005085 if (RHS->isAllOnesValue()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005086 Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005087 return BinaryOperator::CreateSub(
Owen Andersond672ecb2009-07-03 00:17:18 +00005088 Context->getConstantExprSub(NegOp0CI,
5089 Context->getConstantInt(I.getType(), 1)),
5090 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005091 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005092 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersond672ecb2009-07-03 00:17:18 +00005093 Constant *C =
5094 Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005095 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005096
Chris Lattner7c4049c2004-01-12 19:35:11 +00005097 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005098 } else if (Op0I->getOpcode() == Instruction::Or) {
5099 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005100 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005101 Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005102 // Anything in both C1 and C2 is known to be zero, remove it from
5103 // NewRHS.
Owen Andersond672ecb2009-07-03 00:17:18 +00005104 Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5105 NewRHS = Context->getConstantExprAnd(NewRHS,
5106 Context->getConstantExprNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005107 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005108 I.setOperand(0, Op0I->getOperand(0));
5109 I.setOperand(1, NewRHS);
5110 return &I;
5111 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005112 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005113 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005114 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005115
5116 // Try to fold constant and into select arguments.
5117 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005118 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005119 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005120 if (isa<PHINode>(Op0))
5121 if (Instruction *NV = FoldOpIntoPhi(I))
5122 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005123 }
5124
Owen Andersond672ecb2009-07-03 00:17:18 +00005125 if (Value *X = dyn_castNotVal(Op0, Context)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005126 if (X == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005127 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005128
Owen Andersond672ecb2009-07-03 00:17:18 +00005129 if (Value *X = dyn_castNotVal(Op1, Context)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005130 if (X == Op0)
Owen Andersond672ecb2009-07-03 00:17:18 +00005131 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005132
Chris Lattner318bf792007-03-18 22:51:34 +00005133
5134 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5135 if (Op1I) {
5136 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005137 if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005138 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005139 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005140 I.swapOperands();
5141 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005142 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005143 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005144 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005145 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005146 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005147 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005148 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005149 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005150 } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) &&
5151 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005152 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005153 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005154 std::swap(A, B);
5155 }
Chris Lattner318bf792007-03-18 22:51:34 +00005156 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005157 I.swapOperands(); // Simplified below.
5158 std::swap(Op0, Op1);
5159 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005160 }
Chris Lattner318bf792007-03-18 22:51:34 +00005161 }
5162
5163 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5164 if (Op0I) {
5165 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005166 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5167 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005168 if (A == Op1) // (B|A)^B == (A|B)^B
5169 std::swap(A, B);
5170 if (B == Op1) { // (A|B)^B == A & ~B
5171 Instruction *NotB =
Owen Anderson73c6b712009-07-13 20:58:05 +00005172 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
5173 Op1, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005174 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005175 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005176 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005177 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005178 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005179 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005180 } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5181 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005182 if (A == Op1) // (A&B)^A -> (B&A)^A
5183 std::swap(A, B);
5184 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005185 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005186 Instruction *N =
Owen Anderson73c6b712009-07-13 20:58:05 +00005187 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005188 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005189 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005190 }
Chris Lattner318bf792007-03-18 22:51:34 +00005191 }
5192
5193 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5194 if (Op0I && Op1I && Op0I->isShift() &&
5195 Op0I->getOpcode() == Op1I->getOpcode() &&
5196 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5197 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5198 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005199 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005200 Op1I->getOperand(0),
5201 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005202 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005203 Op1I->getOperand(1));
5204 }
5205
5206 if (Op0I && Op1I) {
5207 Value *A, *B, *C, *D;
5208 // (A & B)^(A | B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005209 if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5210 match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005211 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005212 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005213 }
5214 // (A | B)^(A & B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005215 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5216 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005217 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005218 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005219 }
5220
5221 // (A & B)^(C & D)
5222 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005223 match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5224 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005225 // (X & Y)^(X & Y) -> (Y^Z) & X
5226 Value *X = 0, *Y = 0, *Z = 0;
5227 if (A == C)
5228 X = A, Y = B, Z = D;
5229 else if (A == D)
5230 X = A, Y = B, Z = C;
5231 else if (B == C)
5232 X = B, Y = A, Z = D;
5233 else if (B == D)
5234 X = B, Y = A, Z = C;
5235
5236 if (X) {
5237 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005238 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5239 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005240 }
5241 }
5242 }
5243
Reid Spencere4d87aa2006-12-23 06:05:41 +00005244 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5245 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005246 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005247 return R;
5248
Chris Lattner6fc205f2006-05-05 06:39:07 +00005249 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005250 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005251 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005252 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5253 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005254 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005255 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005256 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5257 I.getType(), TD) &&
5258 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5259 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005260 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005261 Op1C->getOperand(0),
5262 I.getName());
5263 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005264 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005265 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005266 }
Chris Lattner99c65742007-10-24 05:38:08 +00005267 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005268
Chris Lattner7e708292002-06-25 16:13:24 +00005269 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005270}
5271
Owen Andersond672ecb2009-07-03 00:17:18 +00005272static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005273 LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005274 return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005275}
Chris Lattnera96879a2004-09-29 17:40:11 +00005276
Dan Gohman6de29f82009-06-15 22:12:54 +00005277static bool HasAddOverflow(ConstantInt *Result,
5278 ConstantInt *In1, ConstantInt *In2,
5279 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005280 if (IsSigned)
5281 if (In2->getValue().isNegative())
5282 return Result->getValue().sgt(In1->getValue());
5283 else
5284 return Result->getValue().slt(In1->getValue());
5285 else
5286 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005287}
5288
Dan Gohman6de29f82009-06-15 22:12:54 +00005289/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005290/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005291static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005292 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005293 bool IsSigned = false) {
5294 Result = Context->getConstantExprAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005295
Dan Gohman6de29f82009-06-15 22:12:54 +00005296 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5297 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005298 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5299 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5300 ExtractElement(In1, Idx, Context),
5301 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005302 IsSigned))
5303 return true;
5304 }
5305 return false;
5306 }
5307
5308 return HasAddOverflow(cast<ConstantInt>(Result),
5309 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5310 IsSigned);
5311}
5312
5313static bool HasSubOverflow(ConstantInt *Result,
5314 ConstantInt *In1, ConstantInt *In2,
5315 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005316 if (IsSigned)
5317 if (In2->getValue().isNegative())
5318 return Result->getValue().slt(In1->getValue());
5319 else
5320 return Result->getValue().sgt(In1->getValue());
5321 else
5322 return Result->getValue().ugt(In1->getValue());
5323}
5324
Dan Gohman6de29f82009-06-15 22:12:54 +00005325/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5326/// overflowed for this type.
5327static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005328 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005329 bool IsSigned = false) {
5330 Result = Context->getConstantExprSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005331
5332 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5333 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005334 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5335 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5336 ExtractElement(In1, Idx, Context),
5337 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005338 IsSigned))
5339 return true;
5340 }
5341 return false;
5342 }
5343
5344 return HasSubOverflow(cast<ConstantInt>(Result),
5345 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5346 IsSigned);
5347}
5348
Chris Lattner574da9b2005-01-13 20:14:25 +00005349/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5350/// code necessary to compute the offset from the base pointer (without adding
5351/// in the base pointer). Return the result as a signed integer of intptr size.
5352static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5353 TargetData &TD = IC.getTargetData();
5354 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005355 const Type *IntPtrTy = TD.getIntPtrType();
Owen Anderson07cf79e2009-07-06 23:00:19 +00005356 LLVMContext *Context = IC.getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00005357 Value *Result = Context->getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005358
5359 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005360 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005361 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005362
Gabor Greif177dd3f2008-06-12 21:37:33 +00005363 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5364 ++i, ++GTI) {
5365 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005366 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005367 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5368 if (OpC->isZero()) continue;
5369
5370 // Handle a struct index, which adds its field offset to the pointer.
5371 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5372 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5373
5374 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005375 Result =
5376 Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005377 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005378 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005379 BinaryOperator::CreateAdd(Result,
Owen Andersond672ecb2009-07-03 00:17:18 +00005380 Context->getConstantInt(IntPtrTy, Size),
Chris Lattnere62f0212007-04-28 04:52:43 +00005381 GEP->getName()+".offs"), I);
5382 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005383 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005384
Owen Andersond672ecb2009-07-03 00:17:18 +00005385 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5386 Constant *OC =
5387 Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5388 Scale = Context->getConstantExprMul(OC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005389 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005390 Result = Context->getConstantExprAdd(RC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005391 else {
5392 // Emit an add instruction.
5393 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005394 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005395 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005396 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005397 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005398 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005399 // Convert to correct type.
5400 if (Op->getType() != IntPtrTy) {
5401 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005402 Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005403 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005404 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5405 true,
5406 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005407 }
5408 if (Size != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005409 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
Chris Lattnere62f0212007-04-28 04:52:43 +00005410 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005411 Op = Context->getConstantExprMul(OpC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005412 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005413 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005414 GEP->getName()+".idx"), I);
5415 }
5416
5417 // Emit an add instruction.
5418 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005419 Result = Context->getConstantExprAdd(cast<Constant>(Op),
Chris Lattnere62f0212007-04-28 04:52:43 +00005420 cast<Constant>(Result));
5421 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005422 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005423 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005424 }
5425 return Result;
5426}
5427
Chris Lattner10c0d912008-04-22 02:53:33 +00005428
Dan Gohman8f080f02009-07-17 22:16:21 +00005429/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5430/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5431/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5432/// be complex, and scales are involved. The above expression would also be
5433/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5434/// This later form is less amenable to optimization though, and we are allowed
5435/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005436///
5437/// If we can't emit an optimized form for this expression, this returns null.
5438///
5439static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5440 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005441 TargetData &TD = IC.getTargetData();
5442 gep_type_iterator GTI = gep_type_begin(GEP);
5443
5444 // Check to see if this gep only has a single variable index. If so, and if
5445 // any constant indices are a multiple of its scale, then we can compute this
5446 // in terms of the scale of the variable index. For example, if the GEP
5447 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5448 // because the expression will cross zero at the same point.
5449 unsigned i, e = GEP->getNumOperands();
5450 int64_t Offset = 0;
5451 for (i = 1; i != e; ++i, ++GTI) {
5452 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5453 // Compute the aggregate offset of constant indices.
5454 if (CI->isZero()) continue;
5455
5456 // Handle a struct index, which adds its field offset to the pointer.
5457 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5458 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5459 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005460 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005461 Offset += Size*CI->getSExtValue();
5462 }
5463 } else {
5464 // Found our variable index.
5465 break;
5466 }
5467 }
5468
5469 // If there are no variable indices, we must have a constant offset, just
5470 // evaluate it the general way.
5471 if (i == e) return 0;
5472
5473 Value *VariableIdx = GEP->getOperand(i);
5474 // Determine the scale factor of the variable element. For example, this is
5475 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005476 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005477
5478 // Verify that there are no other variable indices. If so, emit the hard way.
5479 for (++i, ++GTI; i != e; ++i, ++GTI) {
5480 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5481 if (!CI) return 0;
5482
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 }
5494
5495 // Okay, we know we have a single variable index, which must be a
5496 // pointer/array/vector index. If there is no offset, life is simple, return
5497 // the index.
5498 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5499 if (Offset == 0) {
5500 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5501 // we don't need to bother extending: the extension won't affect where the
5502 // computation crosses zero.
5503 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5504 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5505 VariableIdx->getNameStart(), &I);
5506 return VariableIdx;
5507 }
5508
5509 // Otherwise, there is an index. The computation we will do will be modulo
5510 // the pointer size, so get it.
5511 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5512
5513 Offset &= PtrSizeMask;
5514 VariableScale &= PtrSizeMask;
5515
5516 // To do this transformation, any constant index must be a multiple of the
5517 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5518 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5519 // multiple of the variable scale.
5520 int64_t NewOffs = Offset / (int64_t)VariableScale;
5521 if (Offset != NewOffs*(int64_t)VariableScale)
5522 return 0;
5523
5524 // Okay, we can do this evaluation. Start by converting the index to intptr.
5525 const Type *IntPtrTy = TD.getIntPtrType();
5526 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005527 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005528 true /*SExt*/,
5529 VariableIdx->getNameStart(), &I);
Owen Andersond672ecb2009-07-03 00:17:18 +00005530 Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005531 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005532}
5533
5534
Reid Spencere4d87aa2006-12-23 06:05:41 +00005535/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005536/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005537Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5538 ICmpInst::Predicate Cond,
5539 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005540 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005541
Chris Lattner10c0d912008-04-22 02:53:33 +00005542 // Look through bitcasts.
5543 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5544 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005545
Chris Lattner574da9b2005-01-13 20:14:25 +00005546 Value *PtrBase = GEPLHS->getOperand(0);
5547 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005548 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005549 // This transformation (ignoring the base and scales) is valid because we
5550 // know pointers can't overflow. See if we can output an optimized form.
5551 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5552
5553 // If not, synthesize the offset the hard way.
5554 if (Offset == 0)
5555 Offset = EmitGEPOffset(GEPLHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005556 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersond672ecb2009-07-03 00:17:18 +00005557 Context->getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005558 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005559 // If the base pointers are different, but the indices are the same, just
5560 // compare the base pointer.
5561 if (PtrBase != GEPRHS->getOperand(0)) {
5562 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005563 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005564 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005565 if (IndicesTheSame)
5566 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5567 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5568 IndicesTheSame = false;
5569 break;
5570 }
5571
5572 // If all indices are the same, just compare the base pointers.
5573 if (IndicesTheSame)
Owen Anderson333c4002009-07-09 23:48:35 +00005574 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005575 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005576
5577 // Otherwise, the base pointers are different and the indices are
5578 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005579 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005580 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005581
Chris Lattnere9d782b2005-01-13 22:25:21 +00005582 // If one of the GEPs has all zero indices, recurse.
5583 bool AllZeros = true;
5584 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5585 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5586 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5587 AllZeros = false;
5588 break;
5589 }
5590 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005591 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5592 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005593
5594 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005595 AllZeros = true;
5596 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5597 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5598 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5599 AllZeros = false;
5600 break;
5601 }
5602 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005603 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005604
Chris Lattner4401c9c2005-01-14 00:20:05 +00005605 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5606 // If the GEPs only differ by one index, compare it.
5607 unsigned NumDifferences = 0; // Keep track of # differences.
5608 unsigned DiffOperand = 0; // The operand that differs.
5609 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5610 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005611 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5612 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005613 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005614 NumDifferences = 2;
5615 break;
5616 } else {
5617 if (NumDifferences++) break;
5618 DiffOperand = i;
5619 }
5620 }
5621
5622 if (NumDifferences == 0) // SAME GEP?
5623 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Andersond672ecb2009-07-03 00:17:18 +00005624 Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005625 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005626
Chris Lattner4401c9c2005-01-14 00:20:05 +00005627 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005628 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5629 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005630 // Make sure we do a signed comparison here.
Owen Anderson333c4002009-07-09 23:48:35 +00005631 return new ICmpInst(*Context,
5632 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005633 }
5634 }
5635
Reid Spencere4d87aa2006-12-23 06:05:41 +00005636 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005637 // the result to fold to a constant!
5638 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5639 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5640 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5641 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5642 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005643 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005644 }
5645 }
5646 return 0;
5647}
5648
Chris Lattnera5406232008-05-19 20:18:56 +00005649/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5650///
5651Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5652 Instruction *LHSI,
5653 Constant *RHSC) {
5654 if (!isa<ConstantFP>(RHSC)) return 0;
5655 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5656
5657 // Get the width of the mantissa. We don't want to hack on conversions that
5658 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005659 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005660 if (MantissaWidth == -1) return 0; // Unknown.
5661
5662 // Check to see that the input is converted from an integer type that is small
5663 // enough that preserves all bits. TODO: check here for "known" sign bits.
5664 // 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 +00005665 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005666
5667 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005668 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5669 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005670 ++InputSize;
5671
5672 // If the conversion would lose info, don't hack on this.
5673 if ((int)InputSize > MantissaWidth)
5674 return 0;
5675
5676 // Otherwise, we can potentially simplify the comparison. We know that it
5677 // will always come through as an integer value and we know the constant is
5678 // not a NAN (it would have been previously simplified).
5679 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5680
5681 ICmpInst::Predicate Pred;
5682 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005683 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005684 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005685 case FCmpInst::FCMP_OEQ:
5686 Pred = ICmpInst::ICMP_EQ;
5687 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005688 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005689 case FCmpInst::FCMP_OGT:
5690 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5691 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005692 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005693 case FCmpInst::FCMP_OGE:
5694 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5695 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005696 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005697 case FCmpInst::FCMP_OLT:
5698 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5699 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005700 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005701 case FCmpInst::FCMP_OLE:
5702 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5703 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005704 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005705 case FCmpInst::FCMP_ONE:
5706 Pred = ICmpInst::ICMP_NE;
5707 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005708 case FCmpInst::FCMP_ORD:
Owen Andersonb3056fa2009-07-21 18:03:38 +00005709 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005710 case FCmpInst::FCMP_UNO:
Owen Andersonb3056fa2009-07-21 18:03:38 +00005711 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005712 }
5713
5714 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5715
5716 // Now we know that the APFloat is a normal number, zero or inf.
5717
Chris Lattner85162782008-05-20 03:50:52 +00005718 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005719 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005720 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005721
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005722 if (!LHSUnsigned) {
5723 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5724 // and large values.
5725 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5726 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5727 APFloat::rmNearestTiesToEven);
5728 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5729 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5730 Pred == ICmpInst::ICMP_SLE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005731 return ReplaceInstUsesWith(I, Context->getTrue());
5732 return ReplaceInstUsesWith(I, Context->getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005733 }
5734 } else {
5735 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5736 // +INF and large values.
5737 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5738 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5739 APFloat::rmNearestTiesToEven);
5740 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5741 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5742 Pred == ICmpInst::ICMP_ULE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005743 return ReplaceInstUsesWith(I, Context->getTrue());
5744 return ReplaceInstUsesWith(I, Context->getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005745 }
Chris Lattnera5406232008-05-19 20:18:56 +00005746 }
5747
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005748 if (!LHSUnsigned) {
5749 // See if the RHS value is < SignedMin.
5750 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5751 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5752 APFloat::rmNearestTiesToEven);
5753 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5754 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5755 Pred == ICmpInst::ICMP_SGE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005756 return ReplaceInstUsesWith(I, Context->getTrue());
5757 return ReplaceInstUsesWith(I, Context->getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005758 }
Chris Lattnera5406232008-05-19 20:18:56 +00005759 }
5760
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005761 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5762 // [0, UMAX], but it may still be fractional. See if it is fractional by
5763 // casting the FP value to the integer value and back, checking for equality.
5764 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005765 Constant *RHSInt = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005766 ? Context->getConstantExprFPToUI(RHSC, IntTy)
5767 : Context->getConstantExprFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005768 if (!RHS.isZero()) {
5769 bool Equal = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005770 ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5771 : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005772 if (!Equal) {
5773 // If we had a comparison against a fractional value, we have to adjust
5774 // the compare predicate and sometimes the value. RHSC is rounded towards
5775 // zero at this point.
5776 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005777 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005778 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00005779 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005780 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00005781 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005782 case ICmpInst::ICMP_ULE:
5783 // (float)int <= 4.4 --> int <= 4
5784 // (float)int <= -4.4 --> false
5785 if (RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005786 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005787 break;
5788 case ICmpInst::ICMP_SLE:
5789 // (float)int <= 4.4 --> int <= 4
5790 // (float)int <= -4.4 --> int < -4
5791 if (RHS.isNegative())
5792 Pred = ICmpInst::ICMP_SLT;
5793 break;
5794 case ICmpInst::ICMP_ULT:
5795 // (float)int < -4.4 --> false
5796 // (float)int < 4.4 --> int <= 4
5797 if (RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005798 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005799 Pred = ICmpInst::ICMP_ULE;
5800 break;
5801 case ICmpInst::ICMP_SLT:
5802 // (float)int < -4.4 --> int < -4
5803 // (float)int < 4.4 --> int <= 4
5804 if (!RHS.isNegative())
5805 Pred = ICmpInst::ICMP_SLE;
5806 break;
5807 case ICmpInst::ICMP_UGT:
5808 // (float)int > 4.4 --> int > 4
5809 // (float)int > -4.4 --> true
5810 if (RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005811 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005812 break;
5813 case ICmpInst::ICMP_SGT:
5814 // (float)int > 4.4 --> int > 4
5815 // (float)int > -4.4 --> int >= -4
5816 if (RHS.isNegative())
5817 Pred = ICmpInst::ICMP_SGE;
5818 break;
5819 case ICmpInst::ICMP_UGE:
5820 // (float)int >= -4.4 --> true
5821 // (float)int >= 4.4 --> int > 4
5822 if (!RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005823 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005824 Pred = ICmpInst::ICMP_UGT;
5825 break;
5826 case ICmpInst::ICMP_SGE:
5827 // (float)int >= -4.4 --> int >= -4
5828 // (float)int >= 4.4 --> int > 4
5829 if (!RHS.isNegative())
5830 Pred = ICmpInst::ICMP_SGT;
5831 break;
5832 }
Chris Lattnera5406232008-05-19 20:18:56 +00005833 }
5834 }
5835
5836 // Lower this FP comparison into an appropriate integer version of the
5837 // comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00005838 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005839}
5840
Reid Spencere4d87aa2006-12-23 06:05:41 +00005841Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5842 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005843 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005844
Chris Lattner58e97462007-01-14 19:42:17 +00005845 // Fold trivial predicates.
5846 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005847 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005848 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005849 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005850
5851 // Simplify 'fcmp pred X, X'
5852 if (Op0 == Op1) {
5853 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005854 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005855 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5856 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5857 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Andersonb3056fa2009-07-21 18:03:38 +00005858 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005859 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5860 case FCmpInst::FCMP_OLT: // True if ordered and less than
5861 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Andersonb3056fa2009-07-21 18:03:38 +00005862 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005863
5864 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5865 case FCmpInst::FCMP_ULT: // True if unordered or less than
5866 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5867 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5868 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5869 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersond672ecb2009-07-03 00:17:18 +00005870 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005871 return &I;
5872
5873 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5874 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5875 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5876 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5877 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5878 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersond672ecb2009-07-03 00:17:18 +00005879 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005880 return &I;
5881 }
5882 }
5883
Reid Spencere4d87aa2006-12-23 06:05:41 +00005884 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005885 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005886
Reid Spencere4d87aa2006-12-23 06:05:41 +00005887 // Handle fcmp with constant RHS
5888 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005889 // If the constant is a nan, see if we can fold the comparison based on it.
5890 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5891 if (CFP->getValueAPF().isNaN()) {
5892 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Andersonb3056fa2009-07-21 18:03:38 +00005893 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005894 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5895 "Comparison must be either ordered or unordered!");
5896 // True if unordered.
Owen Andersonb3056fa2009-07-21 18:03:38 +00005897 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005898 }
5899 }
5900
Reid Spencere4d87aa2006-12-23 06:05:41 +00005901 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5902 switch (LHSI->getOpcode()) {
5903 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005904 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5905 // block. If in the same block, we're encouraging jump threading. If
5906 // not, we are just pessimizing the code by making an i1 phi.
5907 if (LHSI->getParent() == I.getParent())
5908 if (Instruction *NV = FoldOpIntoPhi(I))
5909 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005910 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005911 case Instruction::SIToFP:
5912 case Instruction::UIToFP:
5913 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5914 return NV;
5915 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005916 case Instruction::Select:
5917 // If either operand of the select is a constant, we can fold the
5918 // comparison into the select arms, which will cause one to be
5919 // constant folded and the select turned into a bitwise or.
5920 Value *Op1 = 0, *Op2 = 0;
5921 if (LHSI->hasOneUse()) {
5922 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5923 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005924 Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005925 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005926 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005927 LHSI->getOperand(2), RHSC,
5928 I.getName()), I);
5929 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5930 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005931 Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005932 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005933 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005934 LHSI->getOperand(1), RHSC,
5935 I.getName()), I);
5936 }
5937 }
5938
5939 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005940 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005941 break;
5942 }
5943 }
5944
5945 return Changed ? &I : 0;
5946}
5947
5948Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5949 bool Changed = SimplifyCompare(I);
5950 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5951 const Type *Ty = Op0->getType();
5952
5953 // icmp X, X
5954 if (Op0 == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005955 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005956 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005957
5958 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005959 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005960
Reid Spencere4d87aa2006-12-23 06:05:41 +00005961 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005962 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005963 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5964 isa<ConstantPointerNull>(Op0)) &&
5965 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005966 isa<ConstantPointerNull>(Op1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005967 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005968 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005969
Reid Spencere4d87aa2006-12-23 06:05:41 +00005970 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005971 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005972 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005973 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005974 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005975 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005976 InsertNewInstBefore(Xor, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00005977 return BinaryOperator::CreateNot(*Context, Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005978 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005979 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005980 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005981
Reid Spencere4d87aa2006-12-23 06:05:41 +00005982 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005983 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005984 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005985 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Owen Anderson73c6b712009-07-13 20:58:05 +00005986 Instruction *Not = BinaryOperator::CreateNot(*Context,
5987 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005988 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005989 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005990 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005991 case ICmpInst::ICMP_SGT:
5992 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005993 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005994 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00005995 Instruction *Not = BinaryOperator::CreateNot(*Context,
5996 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005997 InsertNewInstBefore(Not, I);
5998 return BinaryOperator::CreateAnd(Not, Op0);
5999 }
6000 case ICmpInst::ICMP_UGE:
6001 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6002 // FALL THROUGH
6003 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Owen Anderson73c6b712009-07-13 20:58:05 +00006004 Instruction *Not = BinaryOperator::CreateNot(*Context,
6005 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006006 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006007 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006008 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006009 case ICmpInst::ICMP_SGE:
6010 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6011 // FALL THROUGH
6012 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00006013 Instruction *Not = BinaryOperator::CreateNot(*Context,
6014 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006015 InsertNewInstBefore(Not, I);
6016 return BinaryOperator::CreateOr(Not, Op0);
6017 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006018 }
Chris Lattner8b170942002-08-09 23:47:40 +00006019 }
6020
Dan Gohman1c8491e2009-04-25 17:12:48 +00006021 unsigned BitWidth = 0;
6022 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006023 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6024 else if (Ty->isIntOrIntVector())
6025 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006026
6027 bool isSignBit = false;
6028
Dan Gohman81b28ce2008-09-16 18:46:06 +00006029 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006030 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006031 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006032
Chris Lattnerb6566012008-01-05 01:18:20 +00006033 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6034 if (I.isEquality() && CI->isNullValue() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006035 match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006036 // (icmp cond A B) if cond is equality
Owen Anderson333c4002009-07-09 23:48:35 +00006037 return new ICmpInst(*Context, I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006038 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006039
Dan Gohman81b28ce2008-09-16 18:46:06 +00006040 // If we have an icmp le or icmp ge instruction, turn it into the
6041 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6042 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006043 switch (I.getPredicate()) {
6044 default: break;
6045 case ICmpInst::ICMP_ULE:
6046 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006047 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006048 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6049 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006050 case ICmpInst::ICMP_SLE:
6051 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006052 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006053 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6054 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006055 case ICmpInst::ICMP_UGE:
6056 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006057 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006058 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6059 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006060 case ICmpInst::ICMP_SGE:
6061 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006062 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006063 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6064 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006065 }
6066
Chris Lattner183661e2008-07-11 05:40:05 +00006067 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006068 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006069 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006070 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6071 }
6072
6073 // See if we can fold the comparison based on range information we can get
6074 // by checking whether bits are known to be zero or one in the input.
6075 if (BitWidth != 0) {
6076 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6077 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6078
6079 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006080 isSignBit ? APInt::getSignBit(BitWidth)
6081 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006082 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006083 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006084 if (SimplifyDemandedBits(I.getOperandUse(1),
6085 APInt::getAllOnesValue(BitWidth),
6086 Op1KnownZero, Op1KnownOne, 0))
6087 return &I;
6088
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006089 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006090 // in. Compute the Min, Max and RHS values based on the known bits. For the
6091 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006092 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6093 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6094 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6095 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6096 Op0Min, Op0Max);
6097 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6098 Op1Min, Op1Max);
6099 } else {
6100 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6101 Op0Min, Op0Max);
6102 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6103 Op1Min, Op1Max);
6104 }
6105
Chris Lattner183661e2008-07-11 05:40:05 +00006106 // If Min and Max are known to be the same, then SimplifyDemandedBits
6107 // figured out that the LHS is a constant. Just constant fold this now so
6108 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006109 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006110 return new ICmpInst(*Context, I.getPredicate(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006111 Context->getConstantInt(Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006112 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006113 return new ICmpInst(*Context, I.getPredicate(), Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006114 Context->getConstantInt(Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006115
Chris Lattner183661e2008-07-11 05:40:05 +00006116 // Based on the range information we know about the LHS, see if we can
6117 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006118 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006119 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006120 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006121 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersonb3056fa2009-07-21 18:03:38 +00006122 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006123 break;
6124 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006125 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersonb3056fa2009-07-21 18:03:38 +00006126 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner84dff672008-07-11 05:08:55 +00006127 break;
6128 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006129 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006130 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006131 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006132 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006133 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006134 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006135 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6136 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006137 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6138 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006139
6140 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6141 if (CI->isMinValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006142 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Owen Anderson73c6b712009-07-13 20:58:05 +00006143 Context->getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006144 }
Chris Lattner84dff672008-07-11 05:08:55 +00006145 break;
6146 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006147 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006148 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006149 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006150 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006151
6152 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006153 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006154 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6155 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006156 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6157 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006158
6159 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6160 if (CI->isMaxValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006161 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006162 Context->getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006163 }
Chris Lattner84dff672008-07-11 05:08:55 +00006164 break;
6165 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006166 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006167 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006168 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006169 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006170 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006171 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006172 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6173 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006174 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6175 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006176 }
Chris Lattner84dff672008-07-11 05:08:55 +00006177 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006178 case ICmpInst::ICMP_SGT:
6179 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006180 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006181 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006182 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006183
6184 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006185 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006186 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6187 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006188 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6189 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006190 }
6191 break;
6192 case ICmpInst::ICMP_SGE:
6193 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6194 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006195 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006196 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006197 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006198 break;
6199 case ICmpInst::ICMP_SLE:
6200 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6201 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006202 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006203 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006204 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006205 break;
6206 case ICmpInst::ICMP_UGE:
6207 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6208 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006209 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006210 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006211 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006212 break;
6213 case ICmpInst::ICMP_ULE:
6214 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6215 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006216 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006217 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006218 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006219 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006220 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006221
6222 // Turn a signed comparison into an unsigned one if both operands
6223 // are known to have the same sign.
6224 if (I.isSignedPredicate() &&
6225 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6226 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Owen Anderson333c4002009-07-09 23:48:35 +00006227 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006228 }
6229
6230 // Test if the ICmpInst instruction is used exclusively by a select as
6231 // part of a minimum or maximum operation. If so, refrain from doing
6232 // any other folding. This helps out other analyses which understand
6233 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6234 // and CodeGen. And in this case, at least one of the comparison
6235 // operands has at least one user besides the compare (the select),
6236 // which would often largely negate the benefit of folding anyway.
6237 if (I.hasOneUse())
6238 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6239 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6240 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6241 return 0;
6242
6243 // See if we are doing a comparison between a constant and an instruction that
6244 // can be folded into the comparison.
6245 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006246 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006247 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006248 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006249 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006250 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6251 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006252 }
6253
Chris Lattner01deb9d2007-04-03 17:43:25 +00006254 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006255 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6256 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6257 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006258 case Instruction::GetElementPtr:
6259 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006260 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006261 bool isAllZeros = true;
6262 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6263 if (!isa<Constant>(LHSI->getOperand(i)) ||
6264 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6265 isAllZeros = false;
6266 break;
6267 }
6268 if (isAllZeros)
Owen Anderson333c4002009-07-09 23:48:35 +00006269 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006270 Context->getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006271 }
6272 break;
6273
Chris Lattner6970b662005-04-23 15:31:55 +00006274 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006275 // Only fold icmp into the PHI if the phi and fcmp are in the same
6276 // block. If in the same block, we're encouraging jump threading. If
6277 // not, we are just pessimizing the code by making an i1 phi.
6278 if (LHSI->getParent() == I.getParent())
6279 if (Instruction *NV = FoldOpIntoPhi(I))
6280 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006281 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006282 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006283 // If either operand of the select is a constant, we can fold the
6284 // comparison into the select arms, which will cause one to be
6285 // constant folded and the select turned into a bitwise or.
6286 Value *Op1 = 0, *Op2 = 0;
6287 if (LHSI->hasOneUse()) {
6288 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6289 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006290 Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006291 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006292 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006293 LHSI->getOperand(2), RHSC,
6294 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006295 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6296 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006297 Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006298 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006299 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006300 LHSI->getOperand(1), RHSC,
6301 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006302 }
6303 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006304
Chris Lattner6970b662005-04-23 15:31:55 +00006305 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006306 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006307 break;
6308 }
Chris Lattner4802d902007-04-06 18:57:34 +00006309 case Instruction::Malloc:
6310 // If we have (malloc != null), and if the malloc has a single use, we
6311 // can assume it is successful and remove the malloc.
6312 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6313 AddToWorkList(LHSI);
Owen Andersond672ecb2009-07-03 00:17:18 +00006314 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006315 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006316 }
6317 break;
6318 }
Chris Lattner6970b662005-04-23 15:31:55 +00006319 }
6320
Reid Spencere4d87aa2006-12-23 06:05:41 +00006321 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006322 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006323 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006324 return NI;
6325 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006326 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6327 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006328 return NI;
6329
Reid Spencere4d87aa2006-12-23 06:05:41 +00006330 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006331 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6332 // now.
6333 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6334 if (isa<PointerType>(Op0->getType()) &&
6335 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006336 // We keep moving the cast from the left operand over to the right
6337 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006338 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006339
Chris Lattner57d86372007-01-06 01:45:59 +00006340 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6341 // so eliminate it as well.
6342 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6343 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006344
Chris Lattnerde90b762003-11-03 04:25:02 +00006345 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006346 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006347 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006348 Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006349 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006350 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006351 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006352 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006353 }
Owen Anderson333c4002009-07-09 23:48:35 +00006354 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006355 }
Chris Lattner57d86372007-01-06 01:45:59 +00006356 }
6357
6358 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006359 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006360 // This comes up when you have code like
6361 // int X = A < B;
6362 // if (X) ...
6363 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006364 // with a constant or another cast from the same type.
6365 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006366 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006367 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006368 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006369
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006370 // See if it's the same type of instruction on the left and right.
6371 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6372 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006373 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006374 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006375 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006376 default: break;
6377 case Instruction::Add:
6378 case Instruction::Sub:
6379 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006380 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Owen Anderson333c4002009-07-09 23:48:35 +00006381 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006382 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006383 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6384 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6385 if (CI->getValue().isSignBit()) {
6386 ICmpInst::Predicate Pred = I.isSignedPredicate()
6387 ? I.getUnsignedPredicate()
6388 : I.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006389 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006390 Op1I->getOperand(0));
6391 }
6392
6393 if (CI->getValue().isMaxSignedValue()) {
6394 ICmpInst::Predicate Pred = I.isSignedPredicate()
6395 ? I.getUnsignedPredicate()
6396 : I.getSignedPredicate();
6397 Pred = I.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006398 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006399 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006400 }
6401 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006402 break;
6403 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006404 if (!I.isEquality())
6405 break;
6406
Nick Lewycky5d52c452008-08-21 05:56:10 +00006407 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6408 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6409 // Mask = -1 >> count-trailing-zeros(Cst).
6410 if (!CI->isZero() && !CI->isOne()) {
6411 const APInt &AP = CI->getValue();
Owen Andersond672ecb2009-07-03 00:17:18 +00006412 ConstantInt *Mask = Context->getConstantInt(
Nick Lewycky5d52c452008-08-21 05:56:10 +00006413 APInt::getLowBitsSet(AP.getBitWidth(),
6414 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006415 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006416 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6417 Mask);
6418 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6419 Mask);
6420 InsertNewInstBefore(And1, I);
6421 InsertNewInstBefore(And2, I);
Owen Anderson333c4002009-07-09 23:48:35 +00006422 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006423 }
6424 }
6425 break;
6426 }
6427 }
6428 }
6429 }
6430
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006431 // ~x < ~y --> y < x
6432 { Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006433 if (match(Op0, m_Not(m_Value(A)), *Context) &&
6434 match(Op1, m_Not(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006435 return new ICmpInst(*Context, I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006436 }
6437
Chris Lattner65b72ba2006-09-18 04:22:48 +00006438 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006439 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006440
6441 // -x == -y --> x == y
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006442 if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6443 match(Op1, m_Neg(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006444 return new ICmpInst(*Context, I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006445
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006446 if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006447 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6448 Value *OtherVal = A == Op1 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006449 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006450 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006451 }
6452
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006453 if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006454 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006455 ConstantInt *C1, *C2;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006456 if (match(B, m_ConstantInt(C1), *Context) &&
6457 match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006458 Constant *NC =
6459 Context->getConstantInt(C1->getValue() ^ C2->getValue());
Chris Lattnercb504b92008-11-16 05:38:51 +00006460 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Owen Anderson333c4002009-07-09 23:48:35 +00006461 return new ICmpInst(*Context, I.getPredicate(), A,
Chris Lattnercb504b92008-11-16 05:38:51 +00006462 InsertNewInstBefore(Xor, I));
6463 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006464
6465 // A^B == A^D -> B == D
Owen Anderson333c4002009-07-09 23:48:35 +00006466 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6467 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6468 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6469 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006470 }
6471 }
6472
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006473 if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006474 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006475 // A == (A^B) -> B == 0
6476 Value *OtherVal = A == Op0 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006477 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006478 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006479 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006480
6481 // (A-B) == A -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006482 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006483 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006484 Context->getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006485
6486 // A == (A-B) -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006487 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006488 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006489 Context->getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006490
Chris Lattner9c2328e2006-11-14 06:06:06 +00006491 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6492 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006493 match(Op0, m_And(m_Value(A), m_Value(B)), *Context) &&
6494 match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006495 Value *X = 0, *Y = 0, *Z = 0;
6496
6497 if (A == C) {
6498 X = B; Y = D; Z = A;
6499 } else if (A == D) {
6500 X = B; Y = C; Z = A;
6501 } else if (B == C) {
6502 X = A; Y = D; Z = B;
6503 } else if (B == D) {
6504 X = A; Y = C; Z = B;
6505 }
6506
6507 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006508 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6509 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006510 I.setOperand(0, Op1);
Owen Andersond672ecb2009-07-03 00:17:18 +00006511 I.setOperand(1, Context->getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006512 return &I;
6513 }
6514 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006515 }
Chris Lattner7e708292002-06-25 16:13:24 +00006516 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006517}
6518
Chris Lattner562ef782007-06-20 23:46:26 +00006519
6520/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6521/// and CmpRHS are both known to be integer constants.
6522Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6523 ConstantInt *DivRHS) {
6524 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6525 const APInt &CmpRHSV = CmpRHS->getValue();
6526
6527 // FIXME: If the operand types don't match the type of the divide
6528 // then don't attempt this transform. The code below doesn't have the
6529 // logic to deal with a signed divide and an unsigned compare (and
6530 // vice versa). This is because (x /s C1) <s C2 produces different
6531 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6532 // (x /u C1) <u C2. Simply casting the operands and result won't
6533 // work. :( The if statement below tests that condition and bails
6534 // if it finds it.
6535 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6536 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6537 return 0;
6538 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006539 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006540 if (DivIsSigned && DivRHS->isAllOnesValue())
6541 return 0; // The overflow computation also screws up here
6542 if (DivRHS->isOne())
6543 return 0; // Not worth bothering, and eliminates some funny cases
6544 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006545
6546 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6547 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6548 // C2 (CI). By solving for X we can turn this into a range check
6549 // instead of computing a divide.
Owen Andersond672ecb2009-07-03 00:17:18 +00006550 Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006551
6552 // Determine if the product overflows by seeing if the product is
6553 // not equal to the divide. Make sure we do the same kind of divide
6554 // as in the LHS instruction that we're folding.
Owen Andersond672ecb2009-07-03 00:17:18 +00006555 bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6556 Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006557
6558 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006559 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006560
Chris Lattner1dbfd482007-06-21 18:11:19 +00006561 // Figure out the interval that is being checked. For example, a comparison
6562 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6563 // Compute this interval based on the constants involved and the signedness of
6564 // the compare/divide. This computes a half-open interval, keeping track of
6565 // whether either value in the interval overflows. After analysis each
6566 // overflow variable is set to 0 if it's corresponding bound variable is valid
6567 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6568 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006569 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006570
Chris Lattner562ef782007-06-20 23:46:26 +00006571 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006572 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006573 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006574 HiOverflow = LoOverflow = ProdOV;
6575 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006576 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006577 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006578 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006579 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00006580 LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS,
6581 Context)));
Chris Lattner562ef782007-06-20 23:46:26 +00006582 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006583 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006584 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6585 HiOverflow = LoOverflow = ProdOV;
6586 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006587 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006588 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006589 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006590 HiBound = AddOne(Prod, Context);
Chris Lattnera6321b42008-10-11 22:55:00 +00006591 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6592 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006593 ConstantInt* DivNeg =
6594 cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6595 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006596 true) ? -1 : 0;
6597 }
Chris Lattner562ef782007-06-20 23:46:26 +00006598 }
Dan Gohman76491272008-02-13 22:09:18 +00006599 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006600 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006601 // e.g. X/-5 op 0 --> [-4, 5)
Owen Andersond672ecb2009-07-03 00:17:18 +00006602 LoBound = AddOne(DivRHS, Context);
6603 HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006604 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6605 HiOverflow = 1; // [INTMIN+1, overflow)
6606 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6607 }
Dan Gohman76491272008-02-13 22:09:18 +00006608 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006609 // e.g. X/-5 op 3 --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006610 HiBound = AddOne(Prod, Context);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006611 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006612 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006613 LoOverflow = AddWithOverflow(LoBound, HiBound,
6614 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006615 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006616 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6617 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006618 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006619 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006620 }
6621
Chris Lattner1dbfd482007-06-21 18:11:19 +00006622 // Dividing by a negative swaps the condition. LT <-> GT
6623 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006624 }
6625
6626 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006627 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006628 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006629 case ICmpInst::ICMP_EQ:
6630 if (LoOverflow && HiOverflow)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006631 return ReplaceInstUsesWith(ICI, Context->getFalse());
Chris Lattner562ef782007-06-20 23:46:26 +00006632 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006633 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006634 ICmpInst::ICMP_UGE, X, LoBound);
6635 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006636 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006637 ICmpInst::ICMP_ULT, X, HiBound);
6638 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006639 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006640 case ICmpInst::ICMP_NE:
6641 if (LoOverflow && HiOverflow)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006642 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner562ef782007-06-20 23:46:26 +00006643 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006644 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006645 ICmpInst::ICMP_ULT, X, LoBound);
6646 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006647 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006648 ICmpInst::ICMP_UGE, X, HiBound);
6649 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006650 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006651 case ICmpInst::ICMP_ULT:
6652 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006653 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006654 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006655 if (LoOverflow == -1) // Low bound is less than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006656 return ReplaceInstUsesWith(ICI, Context->getFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00006657 return new ICmpInst(*Context, Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006658 case ICmpInst::ICMP_UGT:
6659 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006660 if (HiOverflow == +1) // High bound greater than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006661 return ReplaceInstUsesWith(ICI, Context->getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006662 else if (HiOverflow == -1) // High bound less than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006663 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006664 if (Pred == ICmpInst::ICMP_UGT)
Owen Anderson333c4002009-07-09 23:48:35 +00006665 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006666 else
Owen Anderson333c4002009-07-09 23:48:35 +00006667 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006668 }
6669}
6670
6671
Chris Lattner01deb9d2007-04-03 17:43:25 +00006672/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6673///
6674Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6675 Instruction *LHSI,
6676 ConstantInt *RHS) {
6677 const APInt &RHSV = RHS->getValue();
6678
6679 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006680 case Instruction::Trunc:
6681 if (ICI.isEquality() && LHSI->hasOneUse()) {
6682 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6683 // of the high bits truncated out of x are known.
6684 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6685 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6686 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6687 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6688 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6689
6690 // If all the high bits are known, we can do this xform.
6691 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6692 // Pull in the high bits from known-ones set.
6693 APInt NewRHS(RHS->getValue());
6694 NewRHS.zext(SrcBits);
6695 NewRHS |= KnownOne;
Owen Anderson333c4002009-07-09 23:48:35 +00006696 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006697 Context->getConstantInt(NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006698 }
6699 }
6700 break;
6701
Duncan Sands0091bf22007-04-04 06:42:45 +00006702 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006703 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6704 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6705 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006706 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6707 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006708 Value *CompareVal = LHSI->getOperand(0);
6709
6710 // If the sign bit of the XorCST is not set, there is no change to
6711 // the operation, just stop using the Xor.
6712 if (!XorCST->getValue().isNegative()) {
6713 ICI.setOperand(0, CompareVal);
6714 AddToWorkList(LHSI);
6715 return &ICI;
6716 }
6717
6718 // Was the old condition true if the operand is positive?
6719 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6720
6721 // If so, the new one isn't.
6722 isTrueIfPositive ^= true;
6723
6724 if (isTrueIfPositive)
Owen Anderson333c4002009-07-09 23:48:35 +00006725 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006726 SubOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006727 else
Owen Anderson333c4002009-07-09 23:48:35 +00006728 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006729 AddOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006730 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006731
6732 if (LHSI->hasOneUse()) {
6733 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6734 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6735 const APInt &SignBit = XorCST->getValue();
6736 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6737 ? ICI.getUnsignedPredicate()
6738 : ICI.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006739 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006740 Context->getConstantInt(RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006741 }
6742
6743 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006744 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006745 const APInt &NotSignBit = XorCST->getValue();
6746 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6747 ? ICI.getUnsignedPredicate()
6748 : ICI.getSignedPredicate();
6749 Pred = ICI.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006750 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006751 Context->getConstantInt(RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006752 }
6753 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006754 }
6755 break;
6756 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6757 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6758 LHSI->getOperand(0)->hasOneUse()) {
6759 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6760
6761 // If the LHS is an AND of a truncating cast, we can widen the
6762 // and/compare to be the input width without changing the value
6763 // produced, eliminating a cast.
6764 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6765 // We can do this transformation if either the AND constant does not
6766 // have its sign bit set or if it is an equality comparison.
6767 // Extending a relational comparison when we're checking the sign
6768 // bit would not work.
6769 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006770 (ICI.isEquality() ||
6771 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006772 uint32_t BitWidth =
6773 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6774 APInt NewCST = AndCST->getValue();
6775 NewCST.zext(BitWidth);
6776 APInt NewCI = RHSV;
6777 NewCI.zext(BitWidth);
6778 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006779 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006780 Context->getConstantInt(NewCST),LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006781 InsertNewInstBefore(NewAnd, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006782 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
Owen Andersond672ecb2009-07-03 00:17:18 +00006783 Context->getConstantInt(NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006784 }
6785 }
6786
6787 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6788 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6789 // happens a LOT in code produced by the C front-end, for bitfield
6790 // access.
6791 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6792 if (Shift && !Shift->isShift())
6793 Shift = 0;
6794
6795 ConstantInt *ShAmt;
6796 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6797 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6798 const Type *AndTy = AndCST->getType(); // Type of the and.
6799
6800 // We can fold this as long as we can't shift unknown bits
6801 // into the mask. This can only happen with signed shift
6802 // rights, as they sign-extend.
6803 if (ShAmt) {
6804 bool CanFold = Shift->isLogicalShift();
6805 if (!CanFold) {
6806 // To test for the bad case of the signed shr, see if any
6807 // of the bits shifted in could be tested after the mask.
6808 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6809 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6810
6811 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6812 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6813 AndCST->getValue()) == 0)
6814 CanFold = true;
6815 }
6816
6817 if (CanFold) {
6818 Constant *NewCst;
6819 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006820 NewCst = Context->getConstantExprLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006821 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006822 NewCst = Context->getConstantExprShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006823
6824 // Check to see if we are shifting out any of the bits being
6825 // compared.
Owen Andersond672ecb2009-07-03 00:17:18 +00006826 if (Context->getConstantExpr(Shift->getOpcode(),
6827 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006828 // If we shifted bits out, the fold is not going to work out.
6829 // As a special case, check to see if this means that the
6830 // result is always true or false now.
6831 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006832 return ReplaceInstUsesWith(ICI, Context->getFalse());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006833 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006834 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006835 } else {
6836 ICI.setOperand(1, NewCst);
6837 Constant *NewAndCST;
6838 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006839 NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006840 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006841 NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006842 LHSI->setOperand(1, NewAndCST);
6843 LHSI->setOperand(0, Shift->getOperand(0));
6844 AddToWorkList(Shift); // Shift is dead.
6845 AddUsesToWorkList(ICI);
6846 return &ICI;
6847 }
6848 }
6849 }
6850
6851 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6852 // preferable because it allows the C<<Y expression to be hoisted out
6853 // of a loop if Y is invariant and X is not.
6854 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006855 ICI.isEquality() && !Shift->isArithmeticShift() &&
6856 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006857 // Compute C << Y.
6858 Value *NS;
6859 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006860 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006861 Shift->getOperand(1), "tmp");
6862 } else {
6863 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006864 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006865 Shift->getOperand(1), "tmp");
6866 }
6867 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6868
6869 // Compute X & (C << Y).
6870 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006871 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006872 InsertNewInstBefore(NewAnd, ICI);
6873
6874 ICI.setOperand(0, NewAnd);
6875 return &ICI;
6876 }
6877 }
6878 break;
6879
Chris Lattnera0141b92007-07-15 20:42:37 +00006880 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6881 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6882 if (!ShAmt) break;
6883
6884 uint32_t TypeBits = RHSV.getBitWidth();
6885
6886 // Check that the shift amount is in range. If not, don't perform
6887 // undefined shifts. When the shift is visited it will be
6888 // simplified.
6889 if (ShAmt->uge(TypeBits))
6890 break;
6891
6892 if (ICI.isEquality()) {
6893 // If we are comparing against bits always shifted out, the
6894 // comparison cannot succeed.
6895 Constant *Comp =
Owen Andersond672ecb2009-07-03 00:17:18 +00006896 Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6897 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006898 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6899 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersond672ecb2009-07-03 00:17:18 +00006900 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006901 return ReplaceInstUsesWith(ICI, Cst);
6902 }
6903
6904 if (LHSI->hasOneUse()) {
6905 // Otherwise strength reduce the shift into an and.
6906 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6907 Constant *Mask =
Owen Andersond672ecb2009-07-03 00:17:18 +00006908 Context->getConstantInt(APInt::getLowBitsSet(TypeBits,
6909 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006910
Chris Lattnera0141b92007-07-15 20:42:37 +00006911 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006912 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006913 Mask, LHSI->getName()+".mask");
6914 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006915 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00006916 Context->getConstantInt(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006917 }
6918 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006919
6920 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6921 bool TrueIfSigned = false;
6922 if (LHSI->hasOneUse() &&
6923 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6924 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersond672ecb2009-07-03 00:17:18 +00006925 Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006926 (TypeBits-ShAmt->getZExtValue()-1));
6927 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006928 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006929 Mask, LHSI->getName()+".mask");
6930 Value *And = InsertNewInstBefore(AndI, ICI);
6931
Owen Anderson333c4002009-07-09 23:48:35 +00006932 return new ICmpInst(*Context,
6933 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersond672ecb2009-07-03 00:17:18 +00006934 And, Context->getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006935 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006936 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006937 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006938
6939 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006940 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006941 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006942 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006943 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006944
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006945 // Check that the shift amount is in range. If not, don't perform
6946 // undefined shifts. When the shift is visited it will be
6947 // simplified.
6948 uint32_t TypeBits = RHSV.getBitWidth();
6949 if (ShAmt->uge(TypeBits))
6950 break;
6951
6952 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006953
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006954 // If we are comparing against bits always shifted out, the
6955 // comparison cannot succeed.
6956 APInt Comp = RHSV << ShAmtVal;
6957 if (LHSI->getOpcode() == Instruction::LShr)
6958 Comp = Comp.lshr(ShAmtVal);
6959 else
6960 Comp = Comp.ashr(ShAmtVal);
6961
6962 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6963 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersond672ecb2009-07-03 00:17:18 +00006964 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006965 return ReplaceInstUsesWith(ICI, Cst);
6966 }
6967
6968 // Otherwise, check to see if the bits shifted out are known to be zero.
6969 // If so, we can compare against the unshifted value:
6970 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006971 if (LHSI->hasOneUse() &&
6972 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006973 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Owen Anderson333c4002009-07-09 23:48:35 +00006974 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006975 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006976 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006977
Evan Chengf30752c2008-04-23 00:38:06 +00006978 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006979 // Otherwise strength reduce the shift into an and.
6980 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00006981 Constant *Mask = Context->getConstantInt(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006982
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006983 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006984 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006985 Mask, LHSI->getName()+".mask");
6986 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006987 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00006988 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006989 }
6990 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006991 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006992
6993 case Instruction::SDiv:
6994 case Instruction::UDiv:
6995 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6996 // Fold this div into the comparison, producing a range check.
6997 // Determine, based on the divide type, what the range is being
6998 // checked. If there is an overflow on the low or high side, remember
6999 // it, otherwise compute the range [low, hi) bounding the new value.
7000 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007001 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7002 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7003 DivRHS))
7004 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007005 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007006
7007 case Instruction::Add:
7008 // Fold: icmp pred (add, X, C1), C2
7009
7010 if (!ICI.isEquality()) {
7011 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7012 if (!LHSC) break;
7013 const APInt &LHSV = LHSC->getValue();
7014
7015 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7016 .subtract(LHSV);
7017
7018 if (ICI.isSignedPredicate()) {
7019 if (CR.getLower().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007020 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007021 Context->getConstantInt(CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007022 } else if (CR.getUpper().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007023 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007024 Context->getConstantInt(CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007025 }
7026 } else {
7027 if (CR.getLower().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007028 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007029 Context->getConstantInt(CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007030 } else if (CR.getUpper().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007031 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007032 Context->getConstantInt(CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007033 }
7034 }
7035 }
7036 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007037 }
7038
7039 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7040 if (ICI.isEquality()) {
7041 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7042
7043 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7044 // the second operand is a constant, simplify a bit.
7045 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7046 switch (BO->getOpcode()) {
7047 case Instruction::SRem:
7048 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7049 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7050 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7051 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7052 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007053 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007054 BO->getName());
7055 InsertNewInstBefore(NewRem, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007056 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
Owen Andersond672ecb2009-07-03 00:17:18 +00007057 Context->getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007058 }
7059 }
7060 break;
7061 case Instruction::Add:
7062 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7063 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7064 if (BO->hasOneUse())
Owen Anderson333c4002009-07-09 23:48:35 +00007065 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007066 Context->getConstantExprSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007067 } else if (RHSV == 0) {
7068 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7069 // efficiently invertible, or if the add has just this one use.
7070 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7071
Owen Andersond672ecb2009-07-03 00:17:18 +00007072 if (Value *NegVal = dyn_castNegVal(BOp1, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007073 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
Owen Andersond672ecb2009-07-03 00:17:18 +00007074 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007075 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007076 else if (BO->hasOneUse()) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00007077 Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007078 InsertNewInstBefore(Neg, ICI);
7079 Neg->takeName(BO);
Owen Anderson333c4002009-07-09 23:48:35 +00007080 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007081 }
7082 }
7083 break;
7084 case Instruction::Xor:
7085 // For the xor case, we can xor two constants together, eliminating
7086 // the explicit xor.
7087 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Owen Anderson333c4002009-07-09 23:48:35 +00007088 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007089 Context->getConstantExprXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007090
7091 // FALLTHROUGH
7092 case Instruction::Sub:
7093 // Replace (([sub|xor] A, B) != 0) with (A != B)
7094 if (RHSV == 0)
Owen Anderson333c4002009-07-09 23:48:35 +00007095 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007096 BO->getOperand(1));
7097 break;
7098
7099 case Instruction::Or:
7100 // If bits are being or'd in that are not present in the constant we
7101 // are comparing against, then the comparison could never succeed!
7102 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007103 Constant *NotCI = Context->getConstantExprNot(RHS);
7104 if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7105 return ReplaceInstUsesWith(ICI,
7106 Context->getConstantInt(Type::Int1Ty,
7107 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007108 }
7109 break;
7110
7111 case Instruction::And:
7112 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7113 // If bits are being compared against that are and'd out, then the
7114 // comparison can never succeed!
7115 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007116 return ReplaceInstUsesWith(ICI,
7117 Context->getConstantInt(Type::Int1Ty,
7118 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007119
7120 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7121 if (RHS == BOC && RHSV.isPowerOf2())
Owen Anderson333c4002009-07-09 23:48:35 +00007122 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007123 ICmpInst::ICMP_NE, LHSI,
Owen Andersond672ecb2009-07-03 00:17:18 +00007124 Context->getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007125
7126 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007127 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007128 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007129 Constant *Zero = Context->getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007130 ICmpInst::Predicate pred = isICMP_NE ?
7131 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Owen Anderson333c4002009-07-09 23:48:35 +00007132 return new ICmpInst(*Context, pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007133 }
7134
7135 // ((X & ~7) == 0) --> X < 8
7136 if (RHSV == 0 && isHighOnes(BOC)) {
7137 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007138 Constant *NegX = Context->getConstantExprNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007139 ICmpInst::Predicate pred = isICMP_NE ?
7140 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Owen Anderson333c4002009-07-09 23:48:35 +00007141 return new ICmpInst(*Context, pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007142 }
7143 }
7144 default: break;
7145 }
7146 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7147 // Handle icmp {eq|ne} <intrinsic>, intcst.
7148 if (II->getIntrinsicID() == Intrinsic::bswap) {
7149 AddToWorkList(II);
7150 ICI.setOperand(0, II->getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007151 ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007152 return &ICI;
7153 }
7154 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007155 }
7156 return 0;
7157}
7158
7159/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7160/// We only handle extending casts so far.
7161///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007162Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7163 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007164 Value *LHSCIOp = LHSCI->getOperand(0);
7165 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007166 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007167 Value *RHSCIOp;
7168
Chris Lattner8c756c12007-05-05 22:41:33 +00007169 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7170 // integer type is the same size as the pointer type.
7171 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7172 getTargetData().getPointerSizeInBits() ==
7173 cast<IntegerType>(DestTy)->getBitWidth()) {
7174 Value *RHSOp = 0;
7175 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007176 RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007177 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7178 RHSOp = RHSC->getOperand(0);
7179 // If the pointer types don't match, insert a bitcast.
7180 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007181 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007182 }
7183
7184 if (RHSOp)
Owen Anderson333c4002009-07-09 23:48:35 +00007185 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007186 }
7187
7188 // The code below only handles extension cast instructions, so far.
7189 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007190 if (LHSCI->getOpcode() != Instruction::ZExt &&
7191 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007192 return 0;
7193
Reid Spencere4d87aa2006-12-23 06:05:41 +00007194 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7195 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007196
Reid Spencere4d87aa2006-12-23 06:05:41 +00007197 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007198 // Not an extension from the same type?
7199 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007200 if (RHSCIOp->getType() != LHSCIOp->getType())
7201 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007202
Nick Lewycky4189a532008-01-28 03:48:02 +00007203 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007204 // and the other is a zext), then we can't handle this.
7205 if (CI->getOpcode() != LHSCI->getOpcode())
7206 return 0;
7207
Nick Lewycky4189a532008-01-28 03:48:02 +00007208 // Deal with equality cases early.
7209 if (ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007210 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007211
7212 // A signed comparison of sign extended values simplifies into a
7213 // signed comparison.
7214 if (isSignedCmp && isSignedExt)
Owen Anderson333c4002009-07-09 23:48:35 +00007215 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007216
7217 // The other three cases all fold into an unsigned comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00007218 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007219 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007220
Reid Spencere4d87aa2006-12-23 06:05:41 +00007221 // If we aren't dealing with a constant on the RHS, exit early
7222 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7223 if (!CI)
7224 return 0;
7225
7226 // Compute the constant that would happen if we truncated to SrcTy then
7227 // reextended to DestTy.
Owen Andersond672ecb2009-07-03 00:17:18 +00007228 Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7229 Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7230 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007231
7232 // If the re-extended constant didn't change...
7233 if (Res2 == CI) {
7234 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7235 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007236 // %A = sext i16 %X to i32
7237 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007238 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007239 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007240 // because %A may have negative value.
7241 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007242 // However, we allow this when the compare is EQ/NE, because they are
7243 // signless.
7244 if (isSignedExt == isSignedCmp || ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007245 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007246 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007247 }
7248
7249 // The re-extended constant changed so the constant cannot be represented
7250 // in the shorter type. Consequently, we cannot emit a simple comparison.
7251
7252 // First, handle some easy cases. We know the result cannot be equal at this
7253 // point so handle the ICI.isEquality() cases
7254 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersonb3056fa2009-07-21 18:03:38 +00007255 return ReplaceInstUsesWith(ICI, Context->getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007256 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00007257 return ReplaceInstUsesWith(ICI, Context->getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007258
7259 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7260 // should have been folded away previously and not enter in here.
7261 Value *Result;
7262 if (isSignedCmp) {
7263 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007264 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00007265 Result = Context->getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007266 else
Owen Andersonb3056fa2009-07-21 18:03:38 +00007267 Result = Context->getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007268 } else {
7269 // We're performing an unsigned comparison.
7270 if (isSignedExt) {
7271 // We're performing an unsigned comp with a sign extended value.
7272 // This is true if the input is >= 0. [aka >s -1]
Owen Anderson73c6b712009-07-13 20:58:05 +00007273 Constant *NegOne = Context->getAllOnesValue(SrcTy);
Owen Anderson333c4002009-07-09 23:48:35 +00007274 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7275 LHSCIOp, NegOne, ICI.getName()), ICI);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007276 } else {
7277 // Unsigned extend & unsigned compare -> always true.
Owen Andersonb3056fa2009-07-21 18:03:38 +00007278 Result = Context->getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007279 }
7280 }
7281
7282 // Finally, return the value computed.
7283 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007284 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007285 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007286
7287 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7288 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7289 "ICmp should be folded!");
7290 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00007291 return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
Owen Anderson73c6b712009-07-13 20:58:05 +00007292 return BinaryOperator::CreateNot(*Context, Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007293}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007294
Reid Spencer832254e2007-02-02 02:16:23 +00007295Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7296 return commonShiftTransforms(I);
7297}
7298
7299Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7300 return commonShiftTransforms(I);
7301}
7302
7303Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007304 if (Instruction *R = commonShiftTransforms(I))
7305 return R;
7306
7307 Value *Op0 = I.getOperand(0);
7308
7309 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7310 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7311 if (CSI->isAllOnesValue())
7312 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007313
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007314 // See if we can turn a signed shr into an unsigned shr.
7315 if (MaskedValueIsZero(Op0,
7316 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7317 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7318
7319 // Arithmetic shifting an all-sign-bit value is a no-op.
7320 unsigned NumSignBits = ComputeNumSignBits(Op0);
7321 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7322 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007323
Chris Lattner348f6652007-12-06 01:59:46 +00007324 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007325}
7326
7327Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7328 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007329 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007330
7331 // shl X, 0 == X and shr X, 0 == X
7332 // shl 0, X == 0 and shr 0, X == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007333 if (Op1 == Context->getNullValue(Op1->getType()) ||
7334 Op0 == Context->getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007335 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007336
Reid Spencere4d87aa2006-12-23 06:05:41 +00007337 if (isa<UndefValue>(Op0)) {
7338 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007339 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007340 else // undef << X -> 0, undef >>u X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007341 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007342 }
7343 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007344 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7345 return ReplaceInstUsesWith(I, Op0);
7346 else // X << undef, X >>u undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007347 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007348 }
7349
Dan Gohman9004c8a2009-05-21 02:28:33 +00007350 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007351 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007352 return &I;
7353
Chris Lattner2eefe512004-04-09 19:05:30 +00007354 // Try to fold constant and into select arguments.
7355 if (isa<Constant>(Op0))
7356 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007357 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007358 return R;
7359
Reid Spencerb83eb642006-10-20 07:07:24 +00007360 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007361 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7362 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007363 return 0;
7364}
7365
Reid Spencerb83eb642006-10-20 07:07:24 +00007366Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007367 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007368 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007369
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007370 // See if we can simplify any instructions used by the instruction whose sole
7371 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007372 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007373
Dan Gohmana119de82009-06-14 23:30:43 +00007374 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7375 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007376 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007377 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007378 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007379 return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007380 else {
Owen Andersond672ecb2009-07-03 00:17:18 +00007381 I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007382 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007383 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007384 }
7385
7386 // ((X*C1) << C2) == (X * (C1 << C2))
7387 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7388 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7389 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007390 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007391 Context->getConstantExprShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007392
7393 // Try to fold constant and into select arguments.
7394 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7395 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7396 return R;
7397 if (isa<PHINode>(Op0))
7398 if (Instruction *NV = FoldOpIntoPhi(I))
7399 return NV;
7400
Chris Lattner8999dd32007-12-22 09:07:47 +00007401 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7402 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7403 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7404 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7405 // place. Don't try to do this transformation in this case. Also, we
7406 // require that the input operand is a shift-by-constant so that we have
7407 // confidence that the shifts will get folded together. We could do this
7408 // xform in more cases, but it is unlikely to be profitable.
7409 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7410 isa<ConstantInt>(TrOp->getOperand(1))) {
7411 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersond672ecb2009-07-03 00:17:18 +00007412 Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007413 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007414 I.getName());
7415 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7416
7417 // For logical shifts, the truncation has the effect of making the high
7418 // part of the register be zeros. Emulate this by inserting an AND to
7419 // clear the top bits as needed. This 'and' will usually be zapped by
7420 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007421 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7422 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007423 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7424
7425 // The mask we constructed says what the trunc would do if occurring
7426 // between the shifts. We want to know the effect *after* the second
7427 // shift. We know that it is a logical shift by a constant, so adjust the
7428 // mask as appropriate.
7429 if (I.getOpcode() == Instruction::Shl)
7430 MaskV <<= Op1->getZExtValue();
7431 else {
7432 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7433 MaskV = MaskV.lshr(Op1->getZExtValue());
7434 }
7435
Owen Andersond672ecb2009-07-03 00:17:18 +00007436 Instruction *And =
7437 BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV),
7438 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007439 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7440
7441 // Return the value truncated to the interesting size.
7442 return new TruncInst(And, I.getType());
7443 }
7444 }
7445
Chris Lattner4d5542c2006-01-06 07:12:35 +00007446 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007447 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7448 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7449 Value *V1, *V2;
7450 ConstantInt *CC;
7451 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007452 default: break;
7453 case Instruction::Add:
7454 case Instruction::And:
7455 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007456 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007457 // These operators commute.
7458 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007459 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007460 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7461 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007462 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007463 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007464 Op0BO->getName());
7465 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007466 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007467 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007468 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007469 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007470 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersond672ecb2009-07-03 00:17:18 +00007471 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng90b96812007-03-30 05:45:18 +00007472 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007473 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007474
Chris Lattner150f12a2005-09-18 06:30:59 +00007475 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007476 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007477 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007478 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007479 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007480 m_ConstantInt(CC)), *Context) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007481 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007482 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007483 Op0BO->getOperand(0), Op1,
7484 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007485 InsertNewInstBefore(YS, I); // (Y << C)
7486 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007487 BinaryOperator::CreateAnd(V1,
7488 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007489 V1->getName()+".mask");
7490 InsertNewInstBefore(XM, I); // X & (CC << C)
7491
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007492 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007493 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007494 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007495
Reid Spencera07cb7d2007-02-02 14:41:37 +00007496 // FALL THROUGH.
7497 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007498 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007499 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007500 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7501 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007502 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007503 Op0BO->getOperand(1), Op1,
7504 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007505 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007506 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007507 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007508 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007509 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007510 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersond672ecb2009-07-03 00:17:18 +00007511 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng90b96812007-03-30 05:45:18 +00007512 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007513 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007514
Chris Lattner13d4ab42006-05-31 21:14:00 +00007515 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007516 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7517 match(Op0BO->getOperand(0),
7518 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007519 m_ConstantInt(CC)), *Context) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007520 cast<BinaryOperator>(Op0BO->getOperand(0))
7521 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007522 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007523 Op0BO->getOperand(1), Op1,
7524 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007525 InsertNewInstBefore(YS, I); // (Y << C)
7526 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007527 BinaryOperator::CreateAnd(V1,
7528 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007529 V1->getName()+".mask");
7530 InsertNewInstBefore(XM, I); // X & (CC << C)
7531
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007532 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007533 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007534
Chris Lattner11021cb2005-09-18 05:12:10 +00007535 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007536 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007537 }
7538
7539
7540 // If the operand is an bitwise operator with a constant RHS, and the
7541 // shift is the only use, we can pull it out of the shift.
7542 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7543 bool isValid = true; // Valid only for And, Or, Xor
7544 bool highBitSet = false; // Transform if high bit of constant set?
7545
7546 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007547 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007548 case Instruction::Add:
7549 isValid = isLeftShift;
7550 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007551 case Instruction::Or:
7552 case Instruction::Xor:
7553 highBitSet = false;
7554 break;
7555 case Instruction::And:
7556 highBitSet = true;
7557 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007558 }
7559
7560 // If this is a signed shift right, and the high bit is modified
7561 // by the logical operation, do not perform the transformation.
7562 // The highBitSet boolean indicates the value of the high bit of
7563 // the constant which would cause it to be modified for this
7564 // operation.
7565 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007566 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007567 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007568
7569 if (isValid) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007570 Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007571
7572 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007573 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007574 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007575 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007576
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007577 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007578 NewRHS);
7579 }
7580 }
7581 }
7582 }
7583
Chris Lattnerad0124c2006-01-06 07:52:12 +00007584 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007585 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7586 if (ShiftOp && !ShiftOp->isShift())
7587 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007588
Reid Spencerb83eb642006-10-20 07:07:24 +00007589 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007590 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007591 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7592 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007593 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7594 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7595 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007596
Zhou Sheng4351c642007-04-02 08:20:41 +00007597 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007598
7599 const IntegerType *Ty = cast<IntegerType>(I.getType());
7600
7601 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007602 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007603 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7604 // saturates.
7605 if (AmtSum >= TypeBits) {
7606 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007607 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007608 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7609 }
7610
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007611 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersond672ecb2009-07-03 00:17:18 +00007612 Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007613 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7614 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007615 if (AmtSum >= TypeBits)
Owen Andersond672ecb2009-07-03 00:17:18 +00007616 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007617
Chris Lattnerb87056f2007-02-05 00:57:54 +00007618 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersond672ecb2009-07-03 00:17:18 +00007619 return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007620 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7621 I.getOpcode() == Instruction::LShr) {
7622 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007623 if (AmtSum >= TypeBits)
7624 AmtSum = TypeBits-1;
7625
Chris Lattnerb87056f2007-02-05 00:57:54 +00007626 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007627 BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007628 InsertNewInstBefore(Shift, I);
7629
Zhou Shenge9e03f62007-03-28 15:02:20 +00007630 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007631 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007632 }
7633
Chris Lattnerb87056f2007-02-05 00:57:54 +00007634 // Okay, if we get here, one shift must be left, and the other shift must be
7635 // right. See if the amounts are equal.
7636 if (ShiftAmt1 == ShiftAmt2) {
7637 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7638 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007639 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007640 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007641 }
7642 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7643 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007644 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007645 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007646 }
7647 // We can simplify ((X << C) >>s C) into a trunc + sext.
7648 // NOTE: we could do this for any C, but that would make 'unusual' integer
7649 // types. For now, just stick to ones well-supported by the code
7650 // generators.
7651 const Type *SExtType = 0;
7652 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007653 case 1 :
7654 case 8 :
7655 case 16 :
7656 case 32 :
7657 case 64 :
7658 case 128:
Owen Andersond672ecb2009-07-03 00:17:18 +00007659 SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007660 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007661 default: break;
7662 }
7663 if (SExtType) {
7664 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7665 InsertNewInstBefore(NewTrunc, I);
7666 return new SExtInst(NewTrunc, Ty);
7667 }
7668 // Otherwise, we can't handle it yet.
7669 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007670 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007671
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007672 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007673 if (I.getOpcode() == Instruction::Shl) {
7674 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7675 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007676 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007677 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007678 InsertNewInstBefore(Shift, I);
7679
Reid Spencer55702aa2007-03-25 21:11:44 +00007680 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007681 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007682 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007683
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007684 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007685 if (I.getOpcode() == Instruction::LShr) {
7686 assert(ShiftOp->getOpcode() == Instruction::Shl);
7687 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007688 BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007689 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007690
Reid Spencerd5e30f02007-03-26 17:18:58 +00007691 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007692 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007693 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007694
7695 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7696 } else {
7697 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007698 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007699
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007700 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007701 if (I.getOpcode() == Instruction::Shl) {
7702 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7703 ShiftOp->getOpcode() == Instruction::AShr);
7704 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007705 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersond672ecb2009-07-03 00:17:18 +00007706 Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007707 InsertNewInstBefore(Shift, I);
7708
Reid Spencer55702aa2007-03-25 21:11:44 +00007709 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007710 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007711 }
7712
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007713 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007714 if (I.getOpcode() == Instruction::LShr) {
7715 assert(ShiftOp->getOpcode() == Instruction::Shl);
7716 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007717 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007718 InsertNewInstBefore(Shift, I);
7719
Reid Spencer68d27cf2007-03-26 23:45:51 +00007720 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007721 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007722 }
7723
7724 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007725 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007726 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007727 return 0;
7728}
7729
Chris Lattnera1be5662002-05-02 17:06:02 +00007730
Chris Lattnercfd65102005-10-29 04:36:15 +00007731/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7732/// expression. If so, decompose it, returning some value X, such that Val is
7733/// X*Scale+Offset.
7734///
7735static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007736 int &Offset, LLVMContext *Context) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007737 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007738 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007739 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007740 Scale = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00007741 return Context->getConstantInt(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007742 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7743 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7744 if (I->getOpcode() == Instruction::Shl) {
7745 // This is a value scaled by '1 << the shift amt'.
7746 Scale = 1U << RHS->getZExtValue();
7747 Offset = 0;
7748 return I->getOperand(0);
7749 } else if (I->getOpcode() == Instruction::Mul) {
7750 // This value is scaled by 'RHS'.
7751 Scale = RHS->getZExtValue();
7752 Offset = 0;
7753 return I->getOperand(0);
7754 } else if (I->getOpcode() == Instruction::Add) {
7755 // We have X+C. Check to see if we really have (X*C2)+C1,
7756 // where C1 is divisible by C2.
7757 unsigned SubScale;
7758 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007759 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7760 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007761 Offset += RHS->getZExtValue();
7762 Scale = SubScale;
7763 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007764 }
7765 }
7766 }
7767
7768 // Otherwise, we can't look past this.
7769 Scale = 1;
7770 Offset = 0;
7771 return Val;
7772}
7773
7774
Chris Lattnerb3f83972005-10-24 06:03:58 +00007775/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7776/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007777Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007778 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007779 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007780
Chris Lattnerb53c2382005-10-24 06:22:12 +00007781 // Remove any uses of AI that are dead.
7782 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007783
Chris Lattnerb53c2382005-10-24 06:22:12 +00007784 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7785 Instruction *User = cast<Instruction>(*UI++);
7786 if (isInstructionTriviallyDead(User)) {
7787 while (UI != E && *UI == User)
7788 ++UI; // If this instruction uses AI more than once, don't break UI.
7789
Chris Lattnerb53c2382005-10-24 06:22:12 +00007790 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007791 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007792 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007793 }
7794 }
7795
Chris Lattnerb3f83972005-10-24 06:03:58 +00007796 // Get the type really allocated and the type casted to.
7797 const Type *AllocElTy = AI.getAllocatedType();
7798 const Type *CastElTy = PTy->getElementType();
7799 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007800
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007801 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7802 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007803 if (CastElTyAlign < AllocElTyAlign) return 0;
7804
Chris Lattner39387a52005-10-24 06:35:18 +00007805 // If the allocation has multiple uses, only promote it if we are strictly
7806 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007807 // same, we open the door to infinite loops of various kinds. (A reference
7808 // from a dbg.declare doesn't count as a use for this purpose.)
7809 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7810 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007811
Duncan Sands777d2302009-05-09 07:06:46 +00007812 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7813 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007814 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007815
Chris Lattner455fcc82005-10-29 03:19:53 +00007816 // See if we can satisfy the modulus by pulling a scale out of the array
7817 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007818 unsigned ArraySizeScale;
7819 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007820 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007821 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7822 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007823
Chris Lattner455fcc82005-10-29 03:19:53 +00007824 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7825 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007826 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7827 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007828
Chris Lattner455fcc82005-10-29 03:19:53 +00007829 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7830 Value *Amt = 0;
7831 if (Scale == 1) {
7832 Amt = NumElements;
7833 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007834 // If the allocation size is constant, form a constant mul expression
Owen Andersond672ecb2009-07-03 00:17:18 +00007835 Amt = Context->getConstantInt(Type::Int32Ty, Scale);
Reid Spencerc5b206b2006-12-31 05:48:39 +00007836 if (isa<ConstantInt>(NumElements))
Owen Andersond672ecb2009-07-03 00:17:18 +00007837 Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
Dan Gohman6de29f82009-06-15 22:12:54 +00007838 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007839 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007840 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007841 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007842 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007843 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007844 }
7845
Jeff Cohen86796be2007-04-04 16:58:57 +00007846 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007847 Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007848 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007849 Amt = InsertNewInstBefore(Tmp, AI);
7850 }
7851
Chris Lattnerb3f83972005-10-24 06:03:58 +00007852 AllocationInst *New;
7853 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +00007854 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007855 else
Owen Anderson50dead02009-07-15 23:53:25 +00007856 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007857 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007858 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007859
Dale Johannesena0a66372009-03-05 00:39:02 +00007860 // If the allocation has one real use plus a dbg.declare, just remove the
7861 // declare.
7862 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7863 EraseInstFromFunction(*DI);
7864 }
7865 // If the allocation has multiple real uses, insert a cast and change all
7866 // things that used it to use the new cast. This will also hack on CI, but it
7867 // will die soon.
7868 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007869 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007870 // New is the allocation instruction, pointer typed. AI is the original
7871 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7872 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007873 InsertNewInstBefore(NewCast, AI);
7874 AI.replaceAllUsesWith(NewCast);
7875 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007876 return ReplaceInstUsesWith(CI, New);
7877}
7878
Chris Lattner70074e02006-05-13 02:06:03 +00007879/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007880/// and return it as type Ty without inserting any new casts and without
7881/// changing the computed value. This is used by code that tries to decide
7882/// whether promoting or shrinking integer operations to wider or smaller types
7883/// will allow us to eliminate a truncate or extend.
7884///
7885/// This is a truncation operation if Ty is smaller than V->getType(), or an
7886/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007887///
7888/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7889/// should return true if trunc(V) can be computed by computing V in the smaller
7890/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7891/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7892/// efficiently truncated.
7893///
7894/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7895/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7896/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007897bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007898 unsigned CastOpc,
7899 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007900 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007901 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007902 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007903
7904 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007905 if (!I) return false;
7906
Dan Gohman6de29f82009-06-15 22:12:54 +00007907 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007908
Chris Lattner951626b2007-08-02 06:11:14 +00007909 // If this is an extension or truncate, we can often eliminate it.
7910 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7911 // If this is a cast from the destination type, we can trivially eliminate
7912 // it, and this will remove a cast overall.
7913 if (I->getOperand(0)->getType() == Ty) {
7914 // If the first operand is itself a cast, and is eliminable, do not count
7915 // this as an eliminable cast. We would prefer to eliminate those two
7916 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007917 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007918 ++NumCastsRemoved;
7919 return true;
7920 }
7921 }
7922
7923 // We can't extend or shrink something that has multiple uses: doing so would
7924 // require duplicating the instruction in general, which isn't profitable.
7925 if (!I->hasOneUse()) return false;
7926
Evan Chengf35fd542009-01-15 17:01:23 +00007927 unsigned Opc = I->getOpcode();
7928 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007929 case Instruction::Add:
7930 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007931 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007932 case Instruction::And:
7933 case Instruction::Or:
7934 case Instruction::Xor:
7935 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007936 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007937 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007938 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007939 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007940
Eli Friedman070a9812009-07-13 22:46:01 +00007941 case Instruction::UDiv:
7942 case Instruction::URem: {
7943 // UDiv and URem can be truncated if all the truncated bits are zero.
7944 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7945 uint32_t BitWidth = Ty->getScalarSizeInBits();
7946 if (BitWidth < OrigBitWidth) {
7947 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7948 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7949 MaskedValueIsZero(I->getOperand(1), Mask)) {
7950 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7951 NumCastsRemoved) &&
7952 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7953 NumCastsRemoved);
7954 }
7955 }
7956 break;
7957 }
Chris Lattner46b96052006-11-29 07:18:39 +00007958 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007959 // If we are truncating the result of this SHL, and if it's a shift of a
7960 // constant amount, we can always perform a SHL in a smaller type.
7961 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007962 uint32_t BitWidth = Ty->getScalarSizeInBits();
7963 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007964 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007965 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007966 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007967 }
7968 break;
7969 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007970 // If this is a truncate of a logical shr, we can truncate it to a smaller
7971 // lshr iff we know that the bits we would otherwise be shifting in are
7972 // already zeros.
7973 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007974 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7975 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007976 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007977 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007978 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7979 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007980 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007981 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007982 }
7983 }
Chris Lattner46b96052006-11-29 07:18:39 +00007984 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007985 case Instruction::ZExt:
7986 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007987 case Instruction::Trunc:
7988 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007989 // can safely replace it. Note that replacing it does not reduce the number
7990 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007991 if (Opc == CastOpc)
7992 return true;
7993
7994 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007995 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007996 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007997 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007998 case Instruction::Select: {
7999 SelectInst *SI = cast<SelectInst>(I);
8000 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008001 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008002 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008003 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008004 }
Chris Lattner8114b712008-06-18 04:00:49 +00008005 case Instruction::PHI: {
8006 // We can change a phi if we can change all operands.
8007 PHINode *PN = cast<PHINode>(I);
8008 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8009 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008010 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008011 return false;
8012 return true;
8013 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008014 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008015 // TODO: Can handle more cases here.
8016 break;
8017 }
8018
8019 return false;
8020}
8021
8022/// EvaluateInDifferentType - Given an expression that
8023/// CanEvaluateInDifferentType returns true for, actually insert the code to
8024/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008025Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008026 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008027 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +00008028 return Context->getConstantExprIntegerCast(C, Ty,
8029 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008030
8031 // Otherwise, it must be an instruction.
8032 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008033 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008034 unsigned Opc = I->getOpcode();
8035 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008036 case Instruction::Add:
8037 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008038 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008039 case Instruction::And:
8040 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008041 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008042 case Instruction::AShr:
8043 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008044 case Instruction::Shl:
8045 case Instruction::UDiv:
8046 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008047 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008048 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008049 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008050 break;
8051 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008052 case Instruction::Trunc:
8053 case Instruction::ZExt:
8054 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008055 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008056 // just return the source. There's no need to insert it because it is not
8057 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008058 if (I->getOperand(0)->getType() == Ty)
8059 return I->getOperand(0);
8060
Chris Lattner8114b712008-06-18 04:00:49 +00008061 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008062 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008063 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008064 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008065 case Instruction::Select: {
8066 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8067 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8068 Res = SelectInst::Create(I->getOperand(0), True, False);
8069 break;
8070 }
Chris Lattner8114b712008-06-18 04:00:49 +00008071 case Instruction::PHI: {
8072 PHINode *OPN = cast<PHINode>(I);
8073 PHINode *NPN = PHINode::Create(Ty);
8074 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8075 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8076 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8077 }
8078 Res = NPN;
8079 break;
8080 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008081 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008082 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008083 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008084 break;
8085 }
8086
Chris Lattner8114b712008-06-18 04:00:49 +00008087 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008088 return InsertNewInstBefore(Res, *I);
8089}
8090
Reid Spencer3da59db2006-11-27 01:05:10 +00008091/// @brief Implement the transforms common to all CastInst visitors.
8092Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008093 Value *Src = CI.getOperand(0);
8094
Dan Gohman23d9d272007-05-11 21:10:54 +00008095 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008096 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008097 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008098 if (Instruction::CastOps opc =
8099 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8100 // The first cast (CSrc) is eliminable so we need to fix up or replace
8101 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008102 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008103 }
8104 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008105
Reid Spencer3da59db2006-11-27 01:05:10 +00008106 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008107 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8108 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8109 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008110
8111 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008112 if (isa<PHINode>(Src))
8113 if (Instruction *NV = FoldOpIntoPhi(CI))
8114 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008115
Reid Spencer3da59db2006-11-27 01:05:10 +00008116 return 0;
8117}
8118
Chris Lattner46cd5a12009-01-09 05:44:56 +00008119/// FindElementAtOffset - Given a type and a constant offset, determine whether
8120/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008121/// the specified offset. If so, fill them into NewIndices and return the
8122/// resultant element type, otherwise return null.
8123static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8124 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008125 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008126 LLVMContext *Context) {
Chris Lattner3914f722009-01-24 01:00:13 +00008127 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008128
8129 // Start with the index over the outer type. Note that the type size
8130 // might be zero (even if the offset isn't zero) if the indexed type
8131 // is something like [0 x {int, int}]
8132 const Type *IntPtrTy = TD->getIntPtrType();
8133 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008134 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008135 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008136 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008137
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008138 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008139 if (Offset < 0) {
8140 --FirstIdx;
8141 Offset += TySize;
8142 assert(Offset >= 0);
8143 }
8144 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8145 }
8146
Owen Andersond672ecb2009-07-03 00:17:18 +00008147 NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008148
8149 // Index into the types. If we fail, set OrigBase to null.
8150 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008151 // Indexing into tail padding between struct/array elements.
8152 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008153 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008154
Chris Lattner46cd5a12009-01-09 05:44:56 +00008155 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8156 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008157 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8158 "Offset must stay within the indexed type");
8159
Chris Lattner46cd5a12009-01-09 05:44:56 +00008160 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Andersond672ecb2009-07-03 00:17:18 +00008161 NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008162
8163 Offset -= SL->getElementOffset(Elt);
8164 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008165 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008166 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008167 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersond672ecb2009-07-03 00:17:18 +00008168 NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008169 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008170 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008171 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008172 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008173 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008174 }
8175 }
8176
Chris Lattner3914f722009-01-24 01:00:13 +00008177 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008178}
8179
Chris Lattnerd3e28342007-04-27 17:44:50 +00008180/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8181Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8182 Value *Src = CI.getOperand(0);
8183
Chris Lattnerd3e28342007-04-27 17:44:50 +00008184 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008185 // If casting the result of a getelementptr instruction with no offset, turn
8186 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008187 if (GEP->hasAllZeroIndices()) {
8188 // Changing the cast operand is usually not a good idea but it is safe
8189 // here because the pointer operand is being replaced with another
8190 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00008191 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008192 CI.setOperand(0, GEP->getOperand(0));
8193 return &CI;
8194 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008195
8196 // If the GEP has a single use, and the base pointer is a bitcast, and the
8197 // GEP computes a constant offset, see if we can convert these three
8198 // instructions into fewer. This typically happens with unions and other
8199 // non-type-safe code.
8200 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8201 if (GEP->hasAllConstantIndices()) {
8202 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008203 ConstantInt *OffsetV =
8204 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008205 int64_t Offset = OffsetV->getSExtValue();
8206
8207 // Get the base pointer input of the bitcast, and the type it points to.
8208 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8209 const Type *GEPIdxTy =
8210 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008211 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008212 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008213 // If we were able to index down into an element, create the GEP
8214 // and bitcast the result. This eliminates one bitcast, potentially
8215 // two.
8216 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8217 NewIndices.begin(),
8218 NewIndices.end(), "");
8219 InsertNewInstBefore(NGEP, CI);
8220 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008221
Chris Lattner46cd5a12009-01-09 05:44:56 +00008222 if (isa<BitCastInst>(CI))
8223 return new BitCastInst(NGEP, CI.getType());
8224 assert(isa<PtrToIntInst>(CI));
8225 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008226 }
8227 }
8228 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008229 }
8230
8231 return commonCastTransforms(CI);
8232}
8233
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008234/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8235/// type like i42. We don't want to introduce operations on random non-legal
8236/// integer types where they don't already exist in the code. In the future,
8237/// we should consider making this based off target-data, so that 32-bit targets
8238/// won't get i64 operations etc.
8239static bool isSafeIntegerType(const Type *Ty) {
8240 switch (Ty->getPrimitiveSizeInBits()) {
8241 case 8:
8242 case 16:
8243 case 32:
8244 case 64:
8245 return true;
8246 default:
8247 return false;
8248 }
8249}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008250
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008251/// commonIntCastTransforms - This function implements the common transforms
8252/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008253Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8254 if (Instruction *Result = commonCastTransforms(CI))
8255 return Result;
8256
8257 Value *Src = CI.getOperand(0);
8258 const Type *SrcTy = Src->getType();
8259 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008260 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8261 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008262
Reid Spencer3da59db2006-11-27 01:05:10 +00008263 // See if we can simplify any instructions used by the LHS whose sole
8264 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008265 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008266 return &CI;
8267
8268 // If the source isn't an instruction or has more than one use then we
8269 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008270 Instruction *SrcI = dyn_cast<Instruction>(Src);
8271 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008272 return 0;
8273
Chris Lattnerc739cd62007-03-03 05:27:34 +00008274 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008275 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008276 // Only do this if the dest type is a simple type, don't convert the
8277 // expression tree to something weird like i93 unless the source is also
8278 // strange.
8279 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008280 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8281 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008282 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008283 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008284 // eliminates the cast, so it is always a win. If this is a zero-extension,
8285 // we need to do an AND to maintain the clear top-part of the computation,
8286 // so we require that the input have eliminated at least one cast. If this
8287 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008288 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008289 bool DoXForm = false;
8290 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008291 switch (CI.getOpcode()) {
8292 default:
8293 // All the others use floating point so we shouldn't actually
8294 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008295 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008296 case Instruction::Trunc:
8297 DoXForm = true;
8298 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008299 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008300 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008301 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008302 // If it's unnecessary to issue an AND to clear the high bits, it's
8303 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008304 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008305 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8306 if (MaskedValueIsZero(TryRes, Mask))
8307 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008308
8309 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008310 if (TryI->use_empty())
8311 EraseInstFromFunction(*TryI);
8312 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008313 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008314 }
Evan Chengf35fd542009-01-15 17:01:23 +00008315 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008316 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008317 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008318 // If we do not have to emit the truncate + sext pair, then it's always
8319 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008320 //
8321 // It's not safe to eliminate the trunc + sext pair if one of the
8322 // eliminated cast is a truncate. e.g.
8323 // t2 = trunc i32 t1 to i16
8324 // t3 = sext i16 t2 to i32
8325 // !=
8326 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008327 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008328 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8329 if (NumSignBits > (DestBitSize - SrcBitSize))
8330 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008331
8332 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008333 if (TryI->use_empty())
8334 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008335 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008336 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008337 }
Evan Chengf35fd542009-01-15 17:01:23 +00008338 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008339
8340 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008341 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8342 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008343 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8344 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008345 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008346 // Just replace this cast with the result.
8347 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008348
Reid Spencer3da59db2006-11-27 01:05:10 +00008349 assert(Res->getType() == DestTy);
8350 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008351 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008352 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008353 // Just replace this cast with the result.
8354 return ReplaceInstUsesWith(CI, Res);
8355 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008356 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008357
8358 // If the high bits are already zero, just replace this cast with the
8359 // result.
8360 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8361 if (MaskedValueIsZero(Res, Mask))
8362 return ReplaceInstUsesWith(CI, Res);
8363
8364 // We need to emit an AND to clear the high bits.
Owen Andersond672ecb2009-07-03 00:17:18 +00008365 Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
Chris Lattnercd1d6d52007-04-02 05:48:58 +00008366 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008367 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008368 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008369 case Instruction::SExt: {
8370 // If the high bits are already filled with sign bit, just replace this
8371 // cast with the result.
8372 unsigned NumSignBits = ComputeNumSignBits(Res);
8373 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008374 return ReplaceInstUsesWith(CI, Res);
8375
Reid Spencer3da59db2006-11-27 01:05:10 +00008376 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008377 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008378 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8379 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008380 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008381 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008382 }
8383 }
8384
8385 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8386 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8387
8388 switch (SrcI->getOpcode()) {
8389 case Instruction::Add:
8390 case Instruction::Mul:
8391 case Instruction::And:
8392 case Instruction::Or:
8393 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008394 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008395 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8396 // Don't insert two casts unless at least one can be eliminated.
8397 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008398 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman65445c52009-07-13 21:45:57 +00008399 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8400 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008401 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008402 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008403 }
8404 }
8405
8406 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8407 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8408 SrcI->getOpcode() == Instruction::Xor &&
Owen Andersonb3056fa2009-07-21 18:03:38 +00008409 Op1 == Context->getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008410 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008411 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008412 return BinaryOperator::CreateXor(New,
8413 Context->getConstantInt(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008414 }
8415 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008416
Eli Friedman65445c52009-07-13 21:45:57 +00008417 case Instruction::Shl: {
8418 // Canonicalize trunc inside shl, if we can.
8419 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8420 if (CI && DestBitSize < SrcBitSize &&
8421 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8422 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8423 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008424 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008425 }
8426 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008427 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008428 }
8429 return 0;
8430}
8431
Chris Lattner8a9f5712007-04-11 06:57:46 +00008432Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008433 if (Instruction *Result = commonIntCastTransforms(CI))
8434 return Result;
8435
8436 Value *Src = CI.getOperand(0);
8437 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008438 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8439 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008440
8441 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008442 if (DestBitWidth == 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008443 Constant *One = Context->getConstantInt(Src->getType(), 1);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008444 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008445 Value *Zero = Context->getNullValue(Src->getType());
Owen Anderson333c4002009-07-09 23:48:35 +00008446 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008447 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008448
Chris Lattner4f9797d2009-03-24 18:15:30 +00008449 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8450 ConstantInt *ShAmtV = 0;
8451 Value *ShiftOp = 0;
8452 if (Src->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008453 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008454 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8455
8456 // Get a mask for the bits shifting in.
8457 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8458 if (MaskedValueIsZero(ShiftOp, Mask)) {
8459 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersond672ecb2009-07-03 00:17:18 +00008460 return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008461
8462 // Okay, we can shrink this. Truncate the input, then return a new
8463 // shift.
8464 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008465 Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008466 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008467 }
8468 }
8469
8470 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008471}
8472
Evan Chengb98a10e2008-03-24 00:21:34 +00008473/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8474/// in order to eliminate the icmp.
8475Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8476 bool DoXform) {
8477 // If we are just checking for a icmp eq of a single bit and zext'ing it
8478 // to an integer, then shift the bit to the appropriate place and then
8479 // cast to integer to avoid the comparison.
8480 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8481 const APInt &Op1CV = Op1C->getValue();
8482
8483 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8484 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8485 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8486 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8487 if (!DoXform) return ICI;
8488
8489 Value *In = ICI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00008490 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008491 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008492 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008493 In->getName()+".lobit"),
8494 CI);
8495 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008496 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008497 false/*ZExt*/, "tmp", &CI);
8498
8499 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008500 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008501 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008502 In->getName()+".not"),
8503 CI);
8504 }
8505
8506 return ReplaceInstUsesWith(CI, In);
8507 }
8508
8509
8510
8511 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8512 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8513 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8514 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8515 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8516 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8517 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8518 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8519 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8520 // This only works for EQ and NE
8521 ICI->isEquality()) {
8522 // If Op1C some other power of two, convert:
8523 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8524 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8525 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8526 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8527
8528 APInt KnownZeroMask(~KnownZero);
8529 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8530 if (!DoXform) return ICI;
8531
8532 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8533 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8534 // (X&4) == 2 --> false
8535 // (X&4) != 2 --> true
Owen Andersond672ecb2009-07-03 00:17:18 +00008536 Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8537 Res = Context->getConstantExprZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008538 return ReplaceInstUsesWith(CI, Res);
8539 }
8540
8541 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8542 Value *In = ICI->getOperand(0);
8543 if (ShiftAmt) {
8544 // Perform a logical shr by shiftamt.
8545 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008546 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersond672ecb2009-07-03 00:17:18 +00008547 Context->getConstantInt(In->getType(), ShiftAmt),
Evan Chengb98a10e2008-03-24 00:21:34 +00008548 In->getName()+".lobit"), CI);
8549 }
8550
8551 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersond672ecb2009-07-03 00:17:18 +00008552 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008553 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008554 InsertNewInstBefore(cast<Instruction>(In), CI);
8555 }
8556
8557 if (CI.getType() == In->getType())
8558 return ReplaceInstUsesWith(CI, In);
8559 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008560 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008561 }
8562 }
8563 }
8564
8565 return 0;
8566}
8567
Chris Lattner8a9f5712007-04-11 06:57:46 +00008568Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008569 // If one of the common conversion will work ..
8570 if (Instruction *Result = commonIntCastTransforms(CI))
8571 return Result;
8572
8573 Value *Src = CI.getOperand(0);
8574
Chris Lattnera84f47c2009-02-17 20:47:23 +00008575 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8576 // types and if the sizes are just right we can convert this into a logical
8577 // 'and' which will be much cheaper than the pair of casts.
8578 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8579 // Get the sizes of the types involved. We know that the intermediate type
8580 // will be smaller than A or C, but don't know the relation between A and C.
8581 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008582 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8583 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8584 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008585 // If we're actually extending zero bits, then if
8586 // SrcSize < DstSize: zext(a & mask)
8587 // SrcSize == DstSize: a & mask
8588 // SrcSize > DstSize: trunc(a) & mask
8589 if (SrcSize < DstSize) {
8590 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008591 Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008592 Instruction *And =
8593 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8594 InsertNewInstBefore(And, CI);
8595 return new ZExtInst(And, CI.getType());
8596 } else if (SrcSize == DstSize) {
8597 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008598 return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008599 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008600 } else if (SrcSize > DstSize) {
8601 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8602 InsertNewInstBefore(Trunc, CI);
8603 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008604 return BinaryOperator::CreateAnd(Trunc,
8605 Context->getConstantInt(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008606 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008607 }
8608 }
8609
Evan Chengb98a10e2008-03-24 00:21:34 +00008610 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8611 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008612
Evan Chengb98a10e2008-03-24 00:21:34 +00008613 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8614 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8615 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8616 // of the (zext icmp) will be transformed.
8617 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8618 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8619 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8620 (transformZExtICmp(LHS, CI, false) ||
8621 transformZExtICmp(RHS, CI, false))) {
8622 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8623 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008624 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008625 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008626 }
8627
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008628 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008629 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8630 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8631 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8632 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008633 if (TI0->getType() == CI.getType())
8634 return
8635 BinaryOperator::CreateAnd(TI0,
Owen Andersond672ecb2009-07-03 00:17:18 +00008636 Context->getConstantExprZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008637 }
8638
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008639 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8640 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8641 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8642 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8643 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8644 And->getOperand(1) == C)
8645 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8646 Value *TI0 = TI->getOperand(0);
8647 if (TI0->getType() == CI.getType()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008648 Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008649 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8650 InsertNewInstBefore(NewAnd, *And);
8651 return BinaryOperator::CreateXor(NewAnd, ZC);
8652 }
8653 }
8654
Reid Spencer3da59db2006-11-27 01:05:10 +00008655 return 0;
8656}
8657
Chris Lattner8a9f5712007-04-11 06:57:46 +00008658Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008659 if (Instruction *I = commonIntCastTransforms(CI))
8660 return I;
8661
Chris Lattner8a9f5712007-04-11 06:57:46 +00008662 Value *Src = CI.getOperand(0);
8663
Dan Gohman1975d032008-10-30 20:40:10 +00008664 // Canonicalize sign-extend from i1 to a select.
8665 if (Src->getType() == Type::Int1Ty)
8666 return SelectInst::Create(Src,
Owen Anderson73c6b712009-07-13 20:58:05 +00008667 Context->getAllOnesValue(CI.getType()),
Owen Andersond672ecb2009-07-03 00:17:18 +00008668 Context->getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008669
8670 // See if the value being truncated is already sign extended. If so, just
8671 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008672 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008673 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008674 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8675 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8676 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008677 unsigned NumSignBits = ComputeNumSignBits(Op);
8678
8679 if (OpBits == DestBits) {
8680 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8681 // bits, it is already ready.
8682 if (NumSignBits > DestBits-MidBits)
8683 return ReplaceInstUsesWith(CI, Op);
8684 } else if (OpBits < DestBits) {
8685 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8686 // bits, just sext from i32.
8687 if (NumSignBits > OpBits-MidBits)
8688 return new SExtInst(Op, CI.getType(), "tmp");
8689 } else {
8690 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8691 // bits, just truncate to i32.
8692 if (NumSignBits > OpBits-MidBits)
8693 return new TruncInst(Op, CI.getType(), "tmp");
8694 }
8695 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008696
8697 // If the input is a shl/ashr pair of a same constant, then this is a sign
8698 // extension from a smaller value. If we could trust arbitrary bitwidth
8699 // integers, we could turn this into a truncate to the smaller bit and then
8700 // use a sext for the whole extension. Since we don't, look deeper and check
8701 // for a truncate. If the source and dest are the same type, eliminate the
8702 // trunc and extend and just do shifts. For example, turn:
8703 // %a = trunc i32 %i to i8
8704 // %b = shl i8 %a, 6
8705 // %c = ashr i8 %b, 6
8706 // %d = sext i8 %c to i32
8707 // into:
8708 // %a = shl i32 %i, 30
8709 // %d = ashr i32 %a, 30
8710 Value *A = 0;
8711 ConstantInt *BA = 0, *CA = 0;
8712 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008713 m_ConstantInt(CA)), *Context) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008714 BA == CA && isa<TruncInst>(A)) {
8715 Value *I = cast<TruncInst>(A)->getOperand(0);
8716 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008717 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8718 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008719 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersond672ecb2009-07-03 00:17:18 +00008720 Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
Chris Lattner46bbad22008-08-06 07:35:52 +00008721 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8722 CI.getName()), CI);
8723 return BinaryOperator::CreateAShr(I, ShAmtV);
8724 }
8725 }
8726
Chris Lattnerba417832007-04-11 06:12:58 +00008727 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008728}
8729
Chris Lattnerb7530652008-01-27 05:29:54 +00008730/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8731/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008732static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008733 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008734 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008735 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008736 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8737 if (!losesInfo)
Owen Andersond672ecb2009-07-03 00:17:18 +00008738 return Context->getConstantFP(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008739 return 0;
8740}
8741
8742/// LookThroughFPExtensions - If this is an fp extension instruction, look
8743/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008744static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008745 if (Instruction *I = dyn_cast<Instruction>(V))
8746 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008747 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008748
8749 // If this value is a constant, return the constant in the smallest FP type
8750 // that can accurately represent it. This allows us to turn
8751 // (float)((double)X+2.0) into x+2.0f.
8752 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8753 if (CFP->getType() == Type::PPC_FP128Ty)
8754 return V; // No constant folding of this.
8755 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008756 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008757 return V;
8758 if (CFP->getType() == Type::DoubleTy)
8759 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008760 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008761 return V;
8762 // Don't try to shrink to various long double types.
8763 }
8764
8765 return V;
8766}
8767
8768Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8769 if (Instruction *I = commonCastTransforms(CI))
8770 return I;
8771
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008772 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008773 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008774 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008775 // many builtins (sqrt, etc).
8776 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8777 if (OpI && OpI->hasOneUse()) {
8778 switch (OpI->getOpcode()) {
8779 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008780 case Instruction::FAdd:
8781 case Instruction::FSub:
8782 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008783 case Instruction::FDiv:
8784 case Instruction::FRem:
8785 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008786 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8787 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008788 if (LHSTrunc->getType() != SrcTy &&
8789 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008790 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008791 // If the source types were both smaller than the destination type of
8792 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008793 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8794 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008795 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8796 CI.getType(), CI);
8797 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8798 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008799 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008800 }
8801 }
8802 break;
8803 }
8804 }
8805 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008806}
8807
8808Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8809 return commonCastTransforms(CI);
8810}
8811
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008812Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008813 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8814 if (OpI == 0)
8815 return commonCastTransforms(FI);
8816
8817 // fptoui(uitofp(X)) --> X
8818 // fptoui(sitofp(X)) --> X
8819 // This is safe if the intermediate type has enough bits in its mantissa to
8820 // accurately represent all values of X. For example, do not do this with
8821 // i64->float->i64. This is also safe for sitofp case, because any negative
8822 // 'X' value would cause an undefined result for the fptoui.
8823 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8824 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008825 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008826 OpI->getType()->getFPMantissaWidth())
8827 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008828
8829 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008830}
8831
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008832Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008833 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8834 if (OpI == 0)
8835 return commonCastTransforms(FI);
8836
8837 // fptosi(sitofp(X)) --> X
8838 // fptosi(uitofp(X)) --> X
8839 // This is safe if the intermediate type has enough bits in its mantissa to
8840 // accurately represent all values of X. For example, do not do this with
8841 // i64->float->i64. This is also safe for sitofp case, because any negative
8842 // 'X' value would cause an undefined result for the fptoui.
8843 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8844 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008845 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008846 OpI->getType()->getFPMantissaWidth())
8847 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008848
8849 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008850}
8851
8852Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8853 return commonCastTransforms(CI);
8854}
8855
8856Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8857 return commonCastTransforms(CI);
8858}
8859
Chris Lattnera0e69692009-03-24 18:35:40 +00008860Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8861 // If the destination integer type is smaller than the intptr_t type for
8862 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8863 // trunc to be exposed to other transforms. Don't do this for extending
8864 // ptrtoint's, because we don't know if the target sign or zero extends its
8865 // pointers.
Dan Gohman6de29f82009-06-15 22:12:54 +00008866 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008867 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8868 TD->getIntPtrType(),
8869 "tmp"), CI);
8870 return new TruncInst(P, CI.getType());
8871 }
8872
Chris Lattnerd3e28342007-04-27 17:44:50 +00008873 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008874}
8875
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008876Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008877 // If the source integer type is larger than the intptr_t type for
8878 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8879 // allows the trunc to be exposed to other transforms. Don't do this for
8880 // extending inttoptr's, because we don't know if the target sign or zero
8881 // extends to pointers.
Dan Gohman6de29f82009-06-15 22:12:54 +00008882 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008883 TD->getPointerSizeInBits()) {
8884 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8885 TD->getIntPtrType(),
8886 "tmp"), CI);
8887 return new IntToPtrInst(P, CI.getType());
8888 }
8889
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008890 if (Instruction *I = commonCastTransforms(CI))
8891 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008892
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008893 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008894}
8895
Chris Lattnerd3e28342007-04-27 17:44:50 +00008896Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008897 // If the operands are integer typed then apply the integer transforms,
8898 // otherwise just apply the common ones.
8899 Value *Src = CI.getOperand(0);
8900 const Type *SrcTy = Src->getType();
8901 const Type *DestTy = CI.getType();
8902
Eli Friedman7e25d452009-07-13 20:53:00 +00008903 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008904 if (Instruction *I = commonPointerCastTransforms(CI))
8905 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008906 } else {
8907 if (Instruction *Result = commonCastTransforms(CI))
8908 return Result;
8909 }
8910
8911
8912 // Get rid of casts from one type to the same type. These are useless and can
8913 // be replaced by the operand.
8914 if (DestTy == Src->getType())
8915 return ReplaceInstUsesWith(CI, Src);
8916
Reid Spencer3da59db2006-11-27 01:05:10 +00008917 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008918 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8919 const Type *DstElTy = DstPTy->getElementType();
8920 const Type *SrcElTy = SrcPTy->getElementType();
8921
Nate Begeman83ad90a2008-03-31 00:22:16 +00008922 // If the address spaces don't match, don't eliminate the bitcast, which is
8923 // required for changing types.
8924 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8925 return 0;
8926
Chris Lattnerd3e28342007-04-27 17:44:50 +00008927 // If we are casting a malloc or alloca to a pointer to a type of the same
8928 // size, rewrite the allocation instruction to allocate the "right" type.
8929 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8930 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8931 return V;
8932
Chris Lattnerd717c182007-05-05 22:32:24 +00008933 // If the source and destination are pointers, and this cast is equivalent
8934 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008935 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Andersond672ecb2009-07-03 00:17:18 +00008936 Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008937 unsigned NumZeros = 0;
8938 while (SrcElTy != DstElTy &&
8939 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8940 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8941 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8942 ++NumZeros;
8943 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008944
Chris Lattnerd3e28342007-04-27 17:44:50 +00008945 // If we found a path from the src to dest, create the getelementptr now.
8946 if (SrcElTy == DstElTy) {
8947 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008948 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8949 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008950 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008951 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008952
Eli Friedman2451a642009-07-18 23:06:53 +00008953 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8954 if (DestVTy->getNumElements() == 1) {
8955 if (!isa<VectorType>(SrcTy)) {
8956 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
8957 DestVTy->getElementType(), CI);
8958 return InsertElementInst::Create(Context->getUndef(DestTy), Elem,
8959 Context->getNullValue(Type::Int32Ty));
8960 }
8961 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8962 }
8963 }
8964
8965 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8966 if (SrcVTy->getNumElements() == 1) {
8967 if (!isa<VectorType>(DestTy)) {
8968 Instruction *Elem =
8969 new ExtractElementInst(Src, Context->getNullValue(Type::Int32Ty));
8970 InsertNewInstBefore(Elem, CI);
8971 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8972 }
8973 }
8974 }
8975
Reid Spencer3da59db2006-11-27 01:05:10 +00008976 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8977 if (SVI->hasOneUse()) {
8978 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8979 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008980 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008981 cast<VectorType>(DestTy)->getNumElements() ==
8982 SVI->getType()->getNumElements() &&
8983 SVI->getType()->getNumElements() ==
8984 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008985 CastInst *Tmp;
8986 // If either of the operands is a cast from CI.getType(), then
8987 // evaluating the shuffle in the casted destination's type will allow
8988 // us to eliminate at least one cast.
8989 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8990 Tmp->getOperand(0)->getType() == DestTy) ||
8991 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8992 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008993 Value *LHS = InsertCastBefore(Instruction::BitCast,
8994 SVI->getOperand(0), DestTy, CI);
8995 Value *RHS = InsertCastBefore(Instruction::BitCast,
8996 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008997 // Return a new shuffle vector. Use the same element ID's, as we
8998 // know the vector types match #elts.
8999 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009000 }
9001 }
9002 }
9003 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009004 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009005}
9006
Chris Lattnere576b912004-04-09 23:46:01 +00009007/// GetSelectFoldableOperands - We want to turn code that looks like this:
9008/// %C = or %A, %B
9009/// %D = select %cond, %C, %A
9010/// into:
9011/// %C = select %cond, %B, 0
9012/// %D = or %A, %C
9013///
9014/// Assuming that the specified instruction is an operand to the select, return
9015/// a bitmask indicating which operands of this instruction are foldable if they
9016/// equal the other incoming value of the select.
9017///
9018static unsigned GetSelectFoldableOperands(Instruction *I) {
9019 switch (I->getOpcode()) {
9020 case Instruction::Add:
9021 case Instruction::Mul:
9022 case Instruction::And:
9023 case Instruction::Or:
9024 case Instruction::Xor:
9025 return 3; // Can fold through either operand.
9026 case Instruction::Sub: // Can only fold on the amount subtracted.
9027 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009028 case Instruction::LShr:
9029 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009030 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009031 default:
9032 return 0; // Cannot fold
9033 }
9034}
9035
9036/// GetSelectFoldableConstant - For the same transformation as the previous
9037/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009038static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009039 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009040 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009041 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009042 case Instruction::Add:
9043 case Instruction::Sub:
9044 case Instruction::Or:
9045 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009046 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009047 case Instruction::LShr:
9048 case Instruction::AShr:
Owen Andersond672ecb2009-07-03 00:17:18 +00009049 return Context->getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009050 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00009051 return Context->getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009052 case Instruction::Mul:
Owen Andersond672ecb2009-07-03 00:17:18 +00009053 return Context->getConstantInt(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009054 }
9055}
9056
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009057/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9058/// have the same opcode and only one use each. Try to simplify this.
9059Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9060 Instruction *FI) {
9061 if (TI->getNumOperands() == 1) {
9062 // If this is a non-volatile load or a cast from the same type,
9063 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009064 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009065 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9066 return 0;
9067 } else {
9068 return 0; // unknown unary op.
9069 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009070
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009071 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009072 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9073 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009074 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009075 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009076 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009077 }
9078
Reid Spencer832254e2007-02-02 02:16:23 +00009079 // Only handle binary operators here.
9080 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009081 return 0;
9082
9083 // Figure out if the operations have any operands in common.
9084 Value *MatchOp, *OtherOpT, *OtherOpF;
9085 bool MatchIsOpZero;
9086 if (TI->getOperand(0) == FI->getOperand(0)) {
9087 MatchOp = TI->getOperand(0);
9088 OtherOpT = TI->getOperand(1);
9089 OtherOpF = FI->getOperand(1);
9090 MatchIsOpZero = true;
9091 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9092 MatchOp = TI->getOperand(1);
9093 OtherOpT = TI->getOperand(0);
9094 OtherOpF = FI->getOperand(0);
9095 MatchIsOpZero = false;
9096 } else if (!TI->isCommutative()) {
9097 return 0;
9098 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9099 MatchOp = TI->getOperand(0);
9100 OtherOpT = TI->getOperand(1);
9101 OtherOpF = FI->getOperand(0);
9102 MatchIsOpZero = true;
9103 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9104 MatchOp = TI->getOperand(1);
9105 OtherOpT = TI->getOperand(0);
9106 OtherOpF = FI->getOperand(1);
9107 MatchIsOpZero = true;
9108 } else {
9109 return 0;
9110 }
9111
9112 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009113 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9114 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009115 InsertNewInstBefore(NewSI, SI);
9116
9117 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9118 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009119 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009120 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009121 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009122 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009123 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009124 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009125}
9126
Evan Chengde621922009-03-31 20:42:45 +00009127static bool isSelect01(Constant *C1, Constant *C2) {
9128 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9129 if (!C1I)
9130 return false;
9131 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9132 if (!C2I)
9133 return false;
9134 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9135}
9136
9137/// FoldSelectIntoOp - Try fold the select into one of the operands to
9138/// facilitate further optimization.
9139Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9140 Value *FalseVal) {
9141 // See the comment above GetSelectFoldableOperands for a description of the
9142 // transformation we are doing here.
9143 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9144 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9145 !isa<Constant>(FalseVal)) {
9146 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9147 unsigned OpToFold = 0;
9148 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9149 OpToFold = 1;
9150 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9151 OpToFold = 2;
9152 }
9153
9154 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009155 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009156 Value *OOp = TVI->getOperand(2-OpToFold);
9157 // Avoid creating select between 2 constants unless it's selecting
9158 // between 0 and 1.
9159 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9160 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9161 InsertNewInstBefore(NewSel, SI);
9162 NewSel->takeName(TVI);
9163 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9164 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009165 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009166 }
9167 }
9168 }
9169 }
9170 }
9171
9172 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9173 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9174 !isa<Constant>(TrueVal)) {
9175 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9176 unsigned OpToFold = 0;
9177 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9178 OpToFold = 1;
9179 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9180 OpToFold = 2;
9181 }
9182
9183 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009184 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009185 Value *OOp = FVI->getOperand(2-OpToFold);
9186 // Avoid creating select between 2 constants unless it's selecting
9187 // between 0 and 1.
9188 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9189 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9190 InsertNewInstBefore(NewSel, SI);
9191 NewSel->takeName(FVI);
9192 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9193 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009194 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009195 }
9196 }
9197 }
9198 }
9199 }
9200
9201 return 0;
9202}
9203
Dan Gohman81b28ce2008-09-16 18:46:06 +00009204/// visitSelectInstWithICmp - Visit a SelectInst that has an
9205/// ICmpInst as its first operand.
9206///
9207Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9208 ICmpInst *ICI) {
9209 bool Changed = false;
9210 ICmpInst::Predicate Pred = ICI->getPredicate();
9211 Value *CmpLHS = ICI->getOperand(0);
9212 Value *CmpRHS = ICI->getOperand(1);
9213 Value *TrueVal = SI.getTrueValue();
9214 Value *FalseVal = SI.getFalseValue();
9215
9216 // Check cases where the comparison is with a constant that
9217 // can be adjusted to fit the min/max idiom. We may edit ICI in
9218 // place here, so make sure the select is the only user.
9219 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009220 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009221 switch (Pred) {
9222 default: break;
9223 case ICmpInst::ICMP_ULT:
9224 case ICmpInst::ICMP_SLT: {
9225 // X < MIN ? T : F --> F
9226 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9227 return ReplaceInstUsesWith(SI, FalseVal);
9228 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009229 Constant *AdjustedRHS = SubOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009230 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9231 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9232 Pred = ICmpInst::getSwappedPredicate(Pred);
9233 CmpRHS = AdjustedRHS;
9234 std::swap(FalseVal, TrueVal);
9235 ICI->setPredicate(Pred);
9236 ICI->setOperand(1, CmpRHS);
9237 SI.setOperand(1, TrueVal);
9238 SI.setOperand(2, FalseVal);
9239 Changed = true;
9240 }
9241 break;
9242 }
9243 case ICmpInst::ICMP_UGT:
9244 case ICmpInst::ICMP_SGT: {
9245 // X > MAX ? T : F --> F
9246 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9247 return ReplaceInstUsesWith(SI, FalseVal);
9248 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009249 Constant *AdjustedRHS = AddOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009250 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9251 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9252 Pred = ICmpInst::getSwappedPredicate(Pred);
9253 CmpRHS = AdjustedRHS;
9254 std::swap(FalseVal, TrueVal);
9255 ICI->setPredicate(Pred);
9256 ICI->setOperand(1, CmpRHS);
9257 SI.setOperand(1, TrueVal);
9258 SI.setOperand(2, FalseVal);
9259 Changed = true;
9260 }
9261 break;
9262 }
9263 }
9264
Dan Gohman1975d032008-10-30 20:40:10 +00009265 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9266 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009267 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009268 if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9269 match(FalseVal, m_ConstantInt<0>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009270 Pred = ICI->getPredicate();
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009271 else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9272 match(FalseVal, m_ConstantInt<-1>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009273 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9274
Dan Gohman1975d032008-10-30 20:40:10 +00009275 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9276 // If we are just checking for a icmp eq of a single bit and zext'ing it
9277 // to an integer, then shift the bit to the appropriate place and then
9278 // cast to integer to avoid the comparison.
9279 const APInt &Op1CV = CI->getValue();
9280
9281 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9282 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9283 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009284 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009285 Value *In = ICI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00009286 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009287 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009288 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9289 In->getName()+".lobit"),
9290 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009291 if (In->getType() != SI.getType())
9292 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009293 true/*SExt*/, "tmp", ICI);
9294
9295 if (Pred == ICmpInst::ICMP_SGT)
Owen Anderson73c6b712009-07-13 20:58:05 +00009296 In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
Dan Gohman1975d032008-10-30 20:40:10 +00009297 In->getName()+".not"), *ICI);
9298
9299 return ReplaceInstUsesWith(SI, In);
9300 }
9301 }
9302 }
9303
Dan Gohman81b28ce2008-09-16 18:46:06 +00009304 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9305 // Transform (X == Y) ? X : Y -> Y
9306 if (Pred == ICmpInst::ICMP_EQ)
9307 return ReplaceInstUsesWith(SI, FalseVal);
9308 // Transform (X != Y) ? X : Y -> X
9309 if (Pred == ICmpInst::ICMP_NE)
9310 return ReplaceInstUsesWith(SI, TrueVal);
9311 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9312
9313 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9314 // Transform (X == Y) ? Y : X -> X
9315 if (Pred == ICmpInst::ICMP_EQ)
9316 return ReplaceInstUsesWith(SI, FalseVal);
9317 // Transform (X != Y) ? Y : X -> Y
9318 if (Pred == ICmpInst::ICMP_NE)
9319 return ReplaceInstUsesWith(SI, TrueVal);
9320 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9321 }
9322
9323 /// NOTE: if we wanted to, this is where to detect integer ABS
9324
9325 return Changed ? &SI : 0;
9326}
9327
Chris Lattner3d69f462004-03-12 05:52:32 +00009328Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009329 Value *CondVal = SI.getCondition();
9330 Value *TrueVal = SI.getTrueValue();
9331 Value *FalseVal = SI.getFalseValue();
9332
9333 // select true, X, Y -> X
9334 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009335 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009336 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009337
9338 // select C, X, X -> X
9339 if (TrueVal == FalseVal)
9340 return ReplaceInstUsesWith(SI, TrueVal);
9341
Chris Lattnere87597f2004-10-16 18:11:37 +00009342 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9343 return ReplaceInstUsesWith(SI, FalseVal);
9344 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9345 return ReplaceInstUsesWith(SI, TrueVal);
9346 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9347 if (isa<Constant>(TrueVal))
9348 return ReplaceInstUsesWith(SI, TrueVal);
9349 else
9350 return ReplaceInstUsesWith(SI, FalseVal);
9351 }
9352
Reid Spencer4fe16d62007-01-11 18:21:29 +00009353 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009354 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009355 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009356 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009357 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009358 } else {
9359 // Change: A = select B, false, C --> A = and !B, C
9360 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009361 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009362 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009363 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009364 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009365 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009366 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009367 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009368 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009369 } else {
9370 // Change: A = select B, C, true --> A = or !B, C
9371 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009372 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009373 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009374 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009375 }
9376 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009377
9378 // select a, b, a -> a&b
9379 // select a, a, b -> a|b
9380 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009381 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009382 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009383 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009384 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009385
Chris Lattner2eefe512004-04-09 19:05:30 +00009386 // Selecting between two integer constants?
9387 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9388 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009389 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009390 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009391 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009392 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009393 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009394 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009395 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009396 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009397 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009398 }
Chris Lattner457dd822004-06-09 07:59:58 +00009399
Reid Spencere4d87aa2006-12-23 06:05:41 +00009400 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009401 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009402 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009403 // non-constant value, eliminate this whole mess. This corresponds to
9404 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009405 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009406 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009407 cast<Constant>(IC->getOperand(1))->isNullValue())
9408 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9409 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009410 isa<ConstantInt>(ICA->getOperand(1)) &&
9411 (ICA->getOperand(1) == TrueValC ||
9412 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009413 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9414 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009415 // know whether we have a icmp_ne or icmp_eq and whether the
9416 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009417 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009418 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009419 Value *V = ICA;
9420 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009421 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009422 Instruction::Xor, V, ICA->getOperand(1)), SI);
9423 return ReplaceInstUsesWith(SI, V);
9424 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009425 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009426 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009427
9428 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009429 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9430 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009431 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009432 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9433 // This is not safe in general for floating point:
9434 // consider X== -0, Y== +0.
9435 // It becomes safe if either operand is a nonzero constant.
9436 ConstantFP *CFPt, *CFPf;
9437 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9438 !CFPt->getValueAPF().isZero()) ||
9439 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9440 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009441 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009442 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009443 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009444 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009445 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009446 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009447
Reid Spencere4d87aa2006-12-23 06:05:41 +00009448 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009449 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009450 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9451 // This is not safe in general for floating point:
9452 // consider X== -0, Y== +0.
9453 // It becomes safe if either operand is a nonzero constant.
9454 ConstantFP *CFPt, *CFPf;
9455 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9456 !CFPt->getValueAPF().isZero()) ||
9457 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9458 !CFPf->getValueAPF().isZero()))
9459 return ReplaceInstUsesWith(SI, FalseVal);
9460 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009461 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009462 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9463 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009464 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009465 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009466 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009467 }
9468
9469 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009470 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9471 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9472 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009473
Chris Lattner87875da2005-01-13 22:52:24 +00009474 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9475 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9476 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009477 Instruction *AddOp = 0, *SubOp = 0;
9478
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009479 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9480 if (TI->getOpcode() == FI->getOpcode())
9481 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9482 return IV;
9483
9484 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9485 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009486 if ((TI->getOpcode() == Instruction::Sub &&
9487 FI->getOpcode() == Instruction::Add) ||
9488 (TI->getOpcode() == Instruction::FSub &&
9489 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009490 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009491 } else if ((FI->getOpcode() == Instruction::Sub &&
9492 TI->getOpcode() == Instruction::Add) ||
9493 (FI->getOpcode() == Instruction::FSub &&
9494 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009495 AddOp = TI; SubOp = FI;
9496 }
9497
9498 if (AddOp) {
9499 Value *OtherAddOp = 0;
9500 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9501 OtherAddOp = AddOp->getOperand(1);
9502 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9503 OtherAddOp = AddOp->getOperand(0);
9504 }
9505
9506 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009507 // So at this point we know we have (Y -> OtherAddOp):
9508 // select C, (add X, Y), (sub X, Z)
9509 Value *NegVal; // Compute -Z
9510 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009511 NegVal = Context->getConstantExprNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009512 } else {
9513 NegVal = InsertNewInstBefore(
Owen Anderson0a5372e2009-07-13 04:09:18 +00009514 BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9515 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009516 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009517
9518 Value *NewTrueOp = OtherAddOp;
9519 Value *NewFalseOp = NegVal;
9520 if (AddOp != TI)
9521 std::swap(NewTrueOp, NewFalseOp);
9522 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009523 SelectInst::Create(CondVal, NewTrueOp,
9524 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009525
9526 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009527 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009528 }
9529 }
9530 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009531
Chris Lattnere576b912004-04-09 23:46:01 +00009532 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009533 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009534 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9535 if (FoldI)
9536 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009537 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009538
9539 if (BinaryOperator::isNot(CondVal)) {
9540 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9541 SI.setOperand(1, FalseVal);
9542 SI.setOperand(2, TrueVal);
9543 return &SI;
9544 }
9545
Chris Lattner3d69f462004-03-12 05:52:32 +00009546 return 0;
9547}
9548
Dan Gohmaneee962e2008-04-10 18:43:06 +00009549/// EnforceKnownAlignment - If the specified pointer points to an object that
9550/// we control, modify the object's alignment to PrefAlign. This isn't
9551/// often possible though. If alignment is important, a more reliable approach
9552/// is to simply align all global variables and allocation instructions to
9553/// their preferred alignment from the beginning.
9554///
9555static unsigned EnforceKnownAlignment(Value *V,
9556 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009557
Dan Gohmaneee962e2008-04-10 18:43:06 +00009558 User *U = dyn_cast<User>(V);
9559 if (!U) return Align;
9560
Dan Gohmanca178902009-07-17 20:47:02 +00009561 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009562 default: break;
9563 case Instruction::BitCast:
9564 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9565 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009566 // If all indexes are zero, it is just the alignment of the base pointer.
9567 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009568 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009569 if (!isa<Constant>(*i) ||
9570 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009571 AllZeroOperands = false;
9572 break;
9573 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009574
9575 if (AllZeroOperands) {
9576 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009577 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009578 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009579 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009580 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009581 }
9582
9583 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9584 // If there is a large requested alignment and we can, bump up the alignment
9585 // of the global.
9586 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009587 if (GV->getAlignment() >= PrefAlign)
9588 Align = GV->getAlignment();
9589 else {
9590 GV->setAlignment(PrefAlign);
9591 Align = PrefAlign;
9592 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009593 }
9594 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9595 // If there is a requested alignment and if this is an alloca, round up. We
9596 // don't do this for malloc, because some systems can't respect the request.
9597 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009598 if (AI->getAlignment() >= PrefAlign)
9599 Align = AI->getAlignment();
9600 else {
9601 AI->setAlignment(PrefAlign);
9602 Align = PrefAlign;
9603 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009604 }
9605 }
9606
9607 return Align;
9608}
9609
9610/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9611/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9612/// and it is more than the alignment of the ultimate object, see if we can
9613/// increase the alignment of the ultimate object, making this check succeed.
9614unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9615 unsigned PrefAlign) {
9616 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9617 sizeof(PrefAlign) * CHAR_BIT;
9618 APInt Mask = APInt::getAllOnesValue(BitWidth);
9619 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9620 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9621 unsigned TrailZ = KnownZero.countTrailingOnes();
9622 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9623
9624 if (PrefAlign > Align)
9625 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9626
9627 // We don't need to make any adjustment.
9628 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009629}
9630
Chris Lattnerf497b022008-01-13 23:50:23 +00009631Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009632 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009633 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009634 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009635 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009636
9637 if (CopyAlign < MinAlign) {
Owen Andersona547b472009-07-09 18:36:20 +00009638 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9639 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009640 return MI;
9641 }
9642
9643 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9644 // load/store.
9645 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9646 if (MemOpLength == 0) return 0;
9647
Chris Lattner37ac6082008-01-14 00:28:35 +00009648 // Source and destination pointer types are always "i8*" for intrinsic. See
9649 // if the size is something we can handle with a single primitive load/store.
9650 // A single load+store correctly handles overlapping memory in the memmove
9651 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009652 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009653 if (Size == 0) return MI; // Delete this mem transfer.
9654
9655 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009656 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009657
Chris Lattner37ac6082008-01-14 00:28:35 +00009658 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009659 Type *NewPtrTy =
9660 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009661
9662 // Memcpy forces the use of i8* for the source and destination. That means
9663 // that if you're using memcpy to move one double around, you'll get a cast
9664 // from double* to i8*. We'd much rather use a double load+store rather than
9665 // an i64 load+store, here because this improves the odds that the source or
9666 // dest address will be promotable. See if we can find a better type than the
9667 // integer datatype.
9668 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9669 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9670 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9671 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9672 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009673 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009674 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9675 if (STy->getNumElements() == 1)
9676 SrcETy = STy->getElementType(0);
9677 else
9678 break;
9679 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9680 if (ATy->getNumElements() == 1)
9681 SrcETy = ATy->getElementType();
9682 else
9683 break;
9684 } else
9685 break;
9686 }
9687
Dan Gohman8f8e2692008-05-23 01:52:21 +00009688 if (SrcETy->isSingleValueType())
Owen Andersond672ecb2009-07-03 00:17:18 +00009689 NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009690 }
9691 }
9692
9693
Chris Lattnerf497b022008-01-13 23:50:23 +00009694 // If the memcpy/memmove provides better alignment info than we can
9695 // infer, use it.
9696 SrcAlign = std::max(SrcAlign, CopyAlign);
9697 DstAlign = std::max(DstAlign, CopyAlign);
9698
9699 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9700 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009701 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9702 InsertNewInstBefore(L, *MI);
9703 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9704
9705 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009706 MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009707 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009708}
Chris Lattner3d69f462004-03-12 05:52:32 +00009709
Chris Lattner69ea9d22008-04-30 06:39:11 +00009710Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9711 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009712 if (MI->getAlignment() < Alignment) {
Owen Andersona547b472009-07-09 18:36:20 +00009713 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9714 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009715 return MI;
9716 }
9717
9718 // Extract the length and alignment and fill if they are constant.
9719 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9720 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9721 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9722 return 0;
9723 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009724 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009725
9726 // If the length is zero, this is a no-op
9727 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9728
9729 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9730 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009731 const Type *ITy = Context->getIntegerType(Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009732
9733 Value *Dest = MI->getDest();
Owen Andersond672ecb2009-07-03 00:17:18 +00009734 Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009735
9736 // Alignment 0 is identity for alignment 1 for memset, but not store.
9737 if (Alignment == 0) Alignment = 1;
9738
9739 // Extract the fill value and store.
9740 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersond672ecb2009-07-03 00:17:18 +00009741 InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9742 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009743
9744 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009745 MI->setLength(Context->getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009746 return MI;
9747 }
9748
9749 return 0;
9750}
9751
9752
Chris Lattner8b0ea312006-01-13 20:11:04 +00009753/// visitCallInst - CallInst simplification. This mostly only handles folding
9754/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9755/// the heavy lifting.
9756///
Chris Lattner9fe38862003-06-19 17:00:31 +00009757Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009758 // If the caller function is nounwind, mark the call as nounwind, even if the
9759 // callee isn't.
9760 if (CI.getParent()->getParent()->doesNotThrow() &&
9761 !CI.doesNotThrow()) {
9762 CI.setDoesNotThrow();
9763 return &CI;
9764 }
9765
9766
9767
Chris Lattner8b0ea312006-01-13 20:11:04 +00009768 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9769 if (!II) return visitCallSite(&CI);
9770
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009771 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9772 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009773 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009774 bool Changed = false;
9775
9776 // memmove/cpy/set of zero bytes is a noop.
9777 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9778 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9779
Chris Lattner35b9e482004-10-12 04:52:52 +00009780 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009781 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009782 // Replace the instruction with just byte operations. We would
9783 // transform other cases to loads/stores, but we don't know if
9784 // alignment is sufficient.
9785 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009786 }
9787
Chris Lattner35b9e482004-10-12 04:52:52 +00009788 // If we have a memmove and the source operation is a constant global,
9789 // then the source and dest pointers can't alias, so we can change this
9790 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009791 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009792 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9793 if (GVSrc->isConstant()) {
9794 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009795 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9796 const Type *Tys[1];
9797 Tys[0] = CI.getOperand(3)->getType();
9798 CI.setOperand(0,
9799 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009800 Changed = true;
9801 }
Chris Lattnera935db82008-05-28 05:30:41 +00009802
9803 // memmove(x,x,size) -> noop.
9804 if (MMI->getSource() == MMI->getDest())
9805 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009806 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009807
Chris Lattner95a959d2006-03-06 20:18:44 +00009808 // If we can determine a pointer alignment that is bigger than currently
9809 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009810 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009811 if (Instruction *I = SimplifyMemTransfer(MI))
9812 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009813 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9814 if (Instruction *I = SimplifyMemSet(MSI))
9815 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009816 }
9817
Chris Lattner8b0ea312006-01-13 20:11:04 +00009818 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009819 }
9820
9821 switch (II->getIntrinsicID()) {
9822 default: break;
9823 case Intrinsic::bswap:
9824 // bswap(bswap(x)) -> x
9825 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9826 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9827 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9828 break;
9829 case Intrinsic::ppc_altivec_lvx:
9830 case Intrinsic::ppc_altivec_lvxl:
9831 case Intrinsic::x86_sse_loadu_ps:
9832 case Intrinsic::x86_sse2_loadu_pd:
9833 case Intrinsic::x86_sse2_loadu_dq:
9834 // Turn PPC lvx -> load if the pointer is known aligned.
9835 // Turn X86 loadups -> load if the pointer is known aligned.
9836 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9837 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00009838 Context->getPointerTypeUnqual(II->getType()),
Chris Lattner0521e3c2008-06-18 04:33:20 +00009839 CI);
9840 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009841 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009842 break;
9843 case Intrinsic::ppc_altivec_stvx:
9844 case Intrinsic::ppc_altivec_stvxl:
9845 // Turn stvx -> store if the pointer is known aligned.
9846 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9847 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009848 Context->getPointerTypeUnqual(II->getOperand(1)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009849 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9850 return new StoreInst(II->getOperand(1), Ptr);
9851 }
9852 break;
9853 case Intrinsic::x86_sse_storeu_ps:
9854 case Intrinsic::x86_sse2_storeu_pd:
9855 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009856 // Turn X86 storeu -> store if the pointer is known aligned.
9857 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9858 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009859 Context->getPointerTypeUnqual(II->getOperand(2)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009860 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9861 return new StoreInst(II->getOperand(2), Ptr);
9862 }
9863 break;
9864
9865 case Intrinsic::x86_sse_cvttss2si: {
9866 // These intrinsics only demands the 0th element of its input vector. If
9867 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009868 unsigned VWidth =
9869 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9870 APInt DemandedElts(VWidth, 1);
9871 APInt UndefElts(VWidth, 0);
9872 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009873 UndefElts)) {
9874 II->setOperand(1, V);
9875 return II;
9876 }
9877 break;
9878 }
9879
9880 case Intrinsic::ppc_altivec_vperm:
9881 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9882 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9883 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009884
Chris Lattner0521e3c2008-06-18 04:33:20 +00009885 // Check that all of the elements are integer constants or undefs.
9886 bool AllEltsOk = true;
9887 for (unsigned i = 0; i != 16; ++i) {
9888 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9889 !isa<UndefValue>(Mask->getOperand(i))) {
9890 AllEltsOk = false;
9891 break;
9892 }
9893 }
9894
9895 if (AllEltsOk) {
9896 // Cast the input vectors to byte vectors.
9897 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9898 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00009899 Value *Result = Context->getUndef(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009900
Chris Lattner0521e3c2008-06-18 04:33:20 +00009901 // Only extract each element once.
9902 Value *ExtractedElts[32];
9903 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9904
Chris Lattnere2ed0572006-04-06 19:19:17 +00009905 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009906 if (isa<UndefValue>(Mask->getOperand(i)))
9907 continue;
9908 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9909 Idx &= 31; // Match the hardware behavior.
9910
9911 if (ExtractedElts[Idx] == 0) {
9912 Instruction *Elt =
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009913 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
9914 Context->getConstantInt(Type::Int32Ty, Idx&15, false), "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009915 InsertNewInstBefore(Elt, CI);
9916 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009917 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009918
Chris Lattner0521e3c2008-06-18 04:33:20 +00009919 // Insert this value into the result vector.
9920 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009921 Context->getConstantInt(Type::Int32Ty, i, false),
9922 "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009923 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009924 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009925 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009926 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009927 }
9928 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009929
Chris Lattner0521e3c2008-06-18 04:33:20 +00009930 case Intrinsic::stackrestore: {
9931 // If the save is right next to the restore, remove the restore. This can
9932 // happen when variable allocas are DCE'd.
9933 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9934 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9935 BasicBlock::iterator BI = SS;
9936 if (&*++BI == II)
9937 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009938 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009939 }
9940
9941 // Scan down this block to see if there is another stack restore in the
9942 // same block without an intervening call/alloca.
9943 BasicBlock::iterator BI = II;
9944 TerminatorInst *TI = II->getParent()->getTerminator();
9945 bool CannotRemove = false;
9946 for (++BI; &*BI != TI; ++BI) {
9947 if (isa<AllocaInst>(BI)) {
9948 CannotRemove = true;
9949 break;
9950 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009951 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9952 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9953 // If there is a stackrestore below this one, remove this one.
9954 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9955 return EraseInstFromFunction(CI);
9956 // Otherwise, ignore the intrinsic.
9957 } else {
9958 // If we found a non-intrinsic call, we can't remove the stack
9959 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009960 CannotRemove = true;
9961 break;
9962 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009963 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009964 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009965
9966 // If the stack restore is in a return/unwind block and if there are no
9967 // allocas or calls between the restore and the return, nuke the restore.
9968 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9969 return EraseInstFromFunction(CI);
9970 break;
9971 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009972 }
9973
Chris Lattner8b0ea312006-01-13 20:11:04 +00009974 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009975}
9976
9977// InvokeInst simplification
9978//
9979Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009980 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009981}
9982
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009983/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9984/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009985static bool isSafeToEliminateVarargsCast(const CallSite CS,
9986 const CastInst * const CI,
9987 const TargetData * const TD,
9988 const int ix) {
9989 if (!CI->isLosslessCast())
9990 return false;
9991
9992 // The size of ByVal arguments is derived from the type, so we
9993 // can't change to a type with a different size. If the size were
9994 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009995 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009996 return true;
9997
9998 const Type* SrcTy =
9999 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10000 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10001 if (!SrcTy->isSized() || !DstTy->isSized())
10002 return false;
Duncan Sands777d2302009-05-09 07:06:46 +000010003 if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010004 return false;
10005 return true;
10006}
10007
Chris Lattnera44d8a22003-10-07 22:32:43 +000010008// visitCallSite - Improvements for call and invoke instructions.
10009//
10010Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010011 bool Changed = false;
10012
10013 // If the callee is a constexpr cast of a function, attempt to move the cast
10014 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010015 if (transformConstExprCastCall(CS)) return 0;
10016
Chris Lattner6c266db2003-10-07 22:54:13 +000010017 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010018
Chris Lattner08b22ec2005-05-13 07:09:09 +000010019 if (Function *CalleeF = dyn_cast<Function>(Callee))
10020 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10021 Instruction *OldCall = CS.getInstruction();
10022 // If the call and callee calling conventions don't match, this call must
10023 // be unreachable, as the call is undefined.
Owen Andersonb3056fa2009-07-21 18:03:38 +000010024 new StoreInst(Context->getTrue(),
Owen Andersond672ecb2009-07-03 00:17:18 +000010025 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10026 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +000010027 if (!OldCall->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000010028 OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010029 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10030 return EraseInstFromFunction(*OldCall);
10031 return 0;
10032 }
10033
Chris Lattner17be6352004-10-18 02:59:09 +000010034 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10035 // This instruction is not reachable, just remove it. We insert a store to
10036 // undef so that we know that this code is not reachable, despite the fact
10037 // that we can't modify the CFG here.
Owen Andersonb3056fa2009-07-21 18:03:38 +000010038 new StoreInst(Context->getTrue(),
Owen Andersond672ecb2009-07-03 00:17:18 +000010039 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +000010040 CS.getInstruction());
10041
10042 if (!CS.getInstruction()->use_empty())
10043 CS.getInstruction()->
Owen Andersond672ecb2009-07-03 00:17:18 +000010044 replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010045
10046 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10047 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010048 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Andersonb3056fa2009-07-21 18:03:38 +000010049 Context->getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010050 }
Chris Lattner17be6352004-10-18 02:59:09 +000010051 return EraseInstFromFunction(*CS.getInstruction());
10052 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010053
Duncan Sandscdb6d922007-09-17 10:26:40 +000010054 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10055 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10056 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10057 return transformCallThroughTrampoline(CS);
10058
Chris Lattner6c266db2003-10-07 22:54:13 +000010059 const PointerType *PTy = cast<PointerType>(Callee->getType());
10060 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10061 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010062 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010063 // See if we can optimize any arguments passed through the varargs area of
10064 // the call.
10065 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010066 E = CS.arg_end(); I != E; ++I, ++ix) {
10067 CastInst *CI = dyn_cast<CastInst>(*I);
10068 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10069 *I = CI->getOperand(0);
10070 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010071 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010072 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010073 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010074
Duncan Sandsf0c33542007-12-19 21:13:37 +000010075 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010076 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010077 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010078 Changed = true;
10079 }
10080
Chris Lattner6c266db2003-10-07 22:54:13 +000010081 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010082}
10083
Chris Lattner9fe38862003-06-19 17:00:31 +000010084// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10085// attempt to move the cast to the arguments of the call/invoke.
10086//
10087bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10088 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10089 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010090 if (CE->getOpcode() != Instruction::BitCast ||
10091 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010092 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010093 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010094 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010095 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010096
10097 // Okay, this is a cast from a function to a different type. Unless doing so
10098 // would cause a type conversion of one of our arguments, change this call to
10099 // be a direct call with arguments casted to the appropriate types.
10100 //
10101 const FunctionType *FT = Callee->getFunctionType();
10102 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010103 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010104
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010105 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010106 return false; // TODO: Handle multiple return values.
10107
Chris Lattnerf78616b2004-01-14 06:06:08 +000010108 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010109 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010110 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010111 // Conversion is ok if changing from one pointer type to another or from
10112 // a pointer to an integer of the same size.
10113 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +000010114 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +000010115 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010116
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010117 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010118 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010119 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010120 return false; // Cannot transform this return value.
10121
Chris Lattner58d74912008-03-12 17:45:29 +000010122 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010123 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010124 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010125 return false; // Attribute not compatible with transformed value.
10126 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010127
Chris Lattnerf78616b2004-01-14 06:06:08 +000010128 // If the callsite is an invoke instruction, and the return value is used by
10129 // a PHI node in a successor, we cannot change the return type of the call
10130 // because there is no place to put the cast instruction (without breaking
10131 // the critical edge). Bail out in this case.
10132 if (!Caller->use_empty())
10133 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10134 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10135 UI != E; ++UI)
10136 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10137 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010138 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010139 return false;
10140 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010141
10142 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10143 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010144
Chris Lattner9fe38862003-06-19 17:00:31 +000010145 CallSite::arg_iterator AI = CS.arg_begin();
10146 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10147 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010148 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010149
10150 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010151 return false; // Cannot transform this parameter value.
10152
Devang Patel19c87462008-09-26 22:53:05 +000010153 if (CallerPAL.getParamAttributes(i + 1)
10154 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010155 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010156
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010157 // Converting from one pointer type to another or between a pointer and an
10158 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010159 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010160 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10161 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010162 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010163 }
10164
10165 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010166 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010167 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010168
Chris Lattner58d74912008-03-12 17:45:29 +000010169 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10170 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010171 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010172 // won't be dropping them. Check that these extra arguments have attributes
10173 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010174 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10175 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010176 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010177 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010178 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010179 return false;
10180 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010181
Chris Lattner9fe38862003-06-19 17:00:31 +000010182 // Okay, we decided that this is a safe thing to do: go ahead and start
10183 // inserting cast instructions as necessary...
10184 std::vector<Value*> Args;
10185 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010186 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010187 attrVec.reserve(NumCommonArgs);
10188
10189 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010190 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010191
10192 // If the return value is not being used, the type may not be compatible
10193 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010194 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010195
10196 // Add the new return attributes.
10197 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010198 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010199
10200 AI = CS.arg_begin();
10201 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10202 const Type *ParamTy = FT->getParamType(i);
10203 if ((*AI)->getType() == ParamTy) {
10204 Args.push_back(*AI);
10205 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010206 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010207 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010208 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010209 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010210 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010211
10212 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010213 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010214 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010215 }
10216
10217 // If the function takes more arguments than the call was taking, add them
10218 // now...
10219 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000010220 Args.push_back(Context->getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010221
10222 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010223 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010224 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +000010225 cerr << "WARNING: While resolving call to function '"
10226 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010227 } else {
10228 // Add all of the arguments in their promoted form to the arg list...
10229 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10230 const Type *PTy = getPromotedType((*AI)->getType());
10231 if (PTy != (*AI)->getType()) {
10232 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010233 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10234 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010235 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010236 InsertNewInstBefore(Cast, *Caller);
10237 Args.push_back(Cast);
10238 } else {
10239 Args.push_back(*AI);
10240 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010241
Duncan Sandse1e520f2008-01-13 08:02:44 +000010242 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010243 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010244 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010245 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010246 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010247 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010248
Devang Patel19c87462008-09-26 22:53:05 +000010249 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10250 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10251
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010252 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +000010253 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010254
Devang Patel05988662008-09-25 21:00:45 +000010255 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010256
Chris Lattner9fe38862003-06-19 17:00:31 +000010257 Instruction *NC;
10258 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010259 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010260 Args.begin(), Args.end(),
10261 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010262 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010263 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010264 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010265 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10266 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010267 CallInst *CI = cast<CallInst>(Caller);
10268 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010269 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010270 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010271 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010272 }
10273
Chris Lattner6934a042007-02-11 01:23:03 +000010274 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010275 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010276 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010277 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010278 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010279 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010280 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010281
10282 // If this is an invoke instruction, we should insert it after the first
10283 // non-phi, instruction in the normal successor block.
10284 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010285 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010286 InsertNewInstBefore(NC, *I);
10287 } else {
10288 // Otherwise, it's a call, just insert cast right after the call instr
10289 InsertNewInstBefore(NC, *Caller);
10290 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010291 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010292 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000010293 NV = Context->getUndef(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010294 }
10295 }
10296
10297 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10298 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010299 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010300 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010301 return true;
10302}
10303
Duncan Sandscdb6d922007-09-17 10:26:40 +000010304// transformCallThroughTrampoline - Turn a call to a function created by the
10305// init_trampoline intrinsic into a direct call to the underlying function.
10306//
10307Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10308 Value *Callee = CS.getCalledValue();
10309 const PointerType *PTy = cast<PointerType>(Callee->getType());
10310 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010311 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010312
10313 // If the call already has the 'nest' attribute somewhere then give up -
10314 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010315 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010316 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010317
10318 IntrinsicInst *Tramp =
10319 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10320
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010321 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010322 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10323 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10324
Devang Patel05988662008-09-25 21:00:45 +000010325 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010326 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010327 unsigned NestIdx = 1;
10328 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010329 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010330
10331 // Look for a parameter marked with the 'nest' attribute.
10332 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10333 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010334 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010335 // Record the parameter type and any other attributes.
10336 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010337 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010338 break;
10339 }
10340
10341 if (NestTy) {
10342 Instruction *Caller = CS.getInstruction();
10343 std::vector<Value*> NewArgs;
10344 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10345
Devang Patel05988662008-09-25 21:00:45 +000010346 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010347 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010348
Duncan Sandscdb6d922007-09-17 10:26:40 +000010349 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010350 // mean appending it. Likewise for attributes.
10351
Devang Patel19c87462008-09-26 22:53:05 +000010352 // Add any result attributes.
10353 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010354 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010355
Duncan Sandscdb6d922007-09-17 10:26:40 +000010356 {
10357 unsigned Idx = 1;
10358 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10359 do {
10360 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010361 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010362 Value *NestVal = Tramp->getOperand(3);
10363 if (NestVal->getType() != NestTy)
10364 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10365 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010366 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010367 }
10368
10369 if (I == E)
10370 break;
10371
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010372 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010373 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010374 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010375 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010376 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010377
10378 ++Idx, ++I;
10379 } while (1);
10380 }
10381
Devang Patel19c87462008-09-26 22:53:05 +000010382 // Add any function attributes.
10383 if (Attributes Attr = Attrs.getFnAttributes())
10384 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10385
Duncan Sandscdb6d922007-09-17 10:26:40 +000010386 // The trampoline may have been bitcast to a bogus type (FTy).
10387 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010388 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010389
Duncan Sandscdb6d922007-09-17 10:26:40 +000010390 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010391 NewTypes.reserve(FTy->getNumParams()+1);
10392
Duncan Sandscdb6d922007-09-17 10:26:40 +000010393 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010394 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010395 {
10396 unsigned Idx = 1;
10397 FunctionType::param_iterator I = FTy->param_begin(),
10398 E = FTy->param_end();
10399
10400 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010401 if (Idx == NestIdx)
10402 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010403 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010404
10405 if (I == E)
10406 break;
10407
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010408 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010409 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010410
10411 ++Idx, ++I;
10412 } while (1);
10413 }
10414
10415 // Replace the trampoline call with a direct call. Let the generic
10416 // code sort out any function type mismatches.
10417 FunctionType *NewFTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000010418 Context->getFunctionType(FTy->getReturnType(), NewTypes,
10419 FTy->isVarArg());
10420 Constant *NewCallee =
10421 NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10422 NestF : Context->getConstantExprBitCast(NestF,
10423 Context->getPointerTypeUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +000010424 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010425
10426 Instruction *NewCaller;
10427 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010428 NewCaller = InvokeInst::Create(NewCallee,
10429 II->getNormalDest(), II->getUnwindDest(),
10430 NewArgs.begin(), NewArgs.end(),
10431 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010432 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010433 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010434 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010435 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10436 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010437 if (cast<CallInst>(Caller)->isTailCall())
10438 cast<CallInst>(NewCaller)->setTailCall();
10439 cast<CallInst>(NewCaller)->
10440 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010441 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010442 }
10443 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10444 Caller->replaceAllUsesWith(NewCaller);
10445 Caller->eraseFromParent();
10446 RemoveFromWorkList(Caller);
10447 return 0;
10448 }
10449 }
10450
10451 // Replace the trampoline call with a direct call. Since there is no 'nest'
10452 // parameter, there is no need to adjust the argument list. Let the generic
10453 // code sort out any function type mismatches.
10454 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010455 NestF->getType() == PTy ? NestF :
10456 Context->getConstantExprBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010457 CS.setCalledFunction(NewCallee);
10458 return CS.getInstruction();
10459}
10460
Chris Lattner7da52b22006-11-01 04:51:18 +000010461/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10462/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10463/// and a single binop.
10464Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10465 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010466 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010467 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010468 Value *LHSVal = FirstInst->getOperand(0);
10469 Value *RHSVal = FirstInst->getOperand(1);
10470
10471 const Type *LHSType = LHSVal->getType();
10472 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010473
10474 // Scan to see if all operands are the same opcode, all have one use, and all
10475 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010476 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010477 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010478 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010479 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010480 // types or GEP's with different index types.
10481 I->getOperand(0)->getType() != LHSType ||
10482 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010483 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010484
10485 // If they are CmpInst instructions, check their predicates
10486 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10487 if (cast<CmpInst>(I)->getPredicate() !=
10488 cast<CmpInst>(FirstInst)->getPredicate())
10489 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010490
10491 // Keep track of which operand needs a phi node.
10492 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10493 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010494 }
10495
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010496 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010497
Chris Lattner7da52b22006-11-01 04:51:18 +000010498 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010499 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010500 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010501 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010502 NewLHS = PHINode::Create(LHSType,
10503 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010504 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10505 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010506 InsertNewInstBefore(NewLHS, PN);
10507 LHSVal = NewLHS;
10508 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010509
10510 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010511 NewRHS = PHINode::Create(RHSType,
10512 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010513 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10514 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010515 InsertNewInstBefore(NewRHS, PN);
10516 RHSVal = NewRHS;
10517 }
10518
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010519 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010520 if (NewLHS || NewRHS) {
10521 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10522 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10523 if (NewLHS) {
10524 Value *NewInLHS = InInst->getOperand(0);
10525 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10526 }
10527 if (NewRHS) {
10528 Value *NewInRHS = InInst->getOperand(1);
10529 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10530 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010531 }
10532 }
10533
Chris Lattner7da52b22006-11-01 04:51:18 +000010534 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010535 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010536 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Owen Anderson333c4002009-07-09 23:48:35 +000010537 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10538 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010539}
10540
Chris Lattner05f18922008-12-01 02:34:36 +000010541Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10542 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10543
10544 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10545 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010546 // This is true if all GEP bases are allocas and if all indices into them are
10547 // constants.
10548 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010549
10550 // Scan to see if all operands are the same opcode, all have one use, and all
10551 // kill their operands (i.e. the operands have one use).
10552 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10553 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10554 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10555 GEP->getNumOperands() != FirstInst->getNumOperands())
10556 return 0;
10557
Chris Lattner36d3e322009-02-21 00:46:50 +000010558 // Keep track of whether or not all GEPs are of alloca pointers.
10559 if (AllBasePointersAreAllocas &&
10560 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10561 !GEP->hasAllConstantIndices()))
10562 AllBasePointersAreAllocas = false;
10563
Chris Lattner05f18922008-12-01 02:34:36 +000010564 // Compare the operand lists.
10565 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10566 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10567 continue;
10568
10569 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10570 // if one of the PHIs has a constant for the index. The index may be
10571 // substantially cheaper to compute for the constants, so making it a
10572 // variable index could pessimize the path. This also handles the case
10573 // for struct indices, which must always be constant.
10574 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10575 isa<ConstantInt>(GEP->getOperand(op)))
10576 return 0;
10577
10578 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10579 return 0;
10580 FixedOperands[op] = 0; // Needs a PHI.
10581 }
10582 }
10583
Chris Lattner36d3e322009-02-21 00:46:50 +000010584 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010585 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010586 // offset calculation, but all the predecessors will have to materialize the
10587 // stack address into a register anyway. We'd actually rather *clone* the
10588 // load up into the predecessors so that we have a load of a gep of an alloca,
10589 // which can usually all be folded into the load.
10590 if (AllBasePointersAreAllocas)
10591 return 0;
10592
Chris Lattner05f18922008-12-01 02:34:36 +000010593 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10594 // that is variable.
10595 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10596
10597 bool HasAnyPHIs = false;
10598 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10599 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10600 Value *FirstOp = FirstInst->getOperand(i);
10601 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10602 FirstOp->getName()+".pn");
10603 InsertNewInstBefore(NewPN, PN);
10604
10605 NewPN->reserveOperandSpace(e);
10606 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10607 OperandPhis[i] = NewPN;
10608 FixedOperands[i] = NewPN;
10609 HasAnyPHIs = true;
10610 }
10611
10612
10613 // Add all operands to the new PHIs.
10614 if (HasAnyPHIs) {
10615 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10616 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10617 BasicBlock *InBB = PN.getIncomingBlock(i);
10618
10619 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10620 if (PHINode *OpPhi = OperandPhis[op])
10621 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10622 }
10623 }
10624
10625 Value *Base = FixedOperands[0];
10626 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10627 FixedOperands.end());
10628}
10629
10630
Chris Lattner21550882009-02-23 05:56:17 +000010631/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10632/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010633/// obvious the value of the load is not changed from the point of the load to
10634/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010635///
10636/// Finally, it is safe, but not profitable, to sink a load targetting a
10637/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10638/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010639static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010640 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10641
10642 for (++BBI; BBI != E; ++BBI)
10643 if (BBI->mayWriteToMemory())
10644 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010645
10646 // Check for non-address taken alloca. If not address-taken already, it isn't
10647 // profitable to do this xform.
10648 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10649 bool isAddressTaken = false;
10650 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10651 UI != E; ++UI) {
10652 if (isa<LoadInst>(UI)) continue;
10653 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10654 // If storing TO the alloca, then the address isn't taken.
10655 if (SI->getOperand(1) == AI) continue;
10656 }
10657 isAddressTaken = true;
10658 break;
10659 }
10660
Chris Lattner36d3e322009-02-21 00:46:50 +000010661 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010662 return false;
10663 }
10664
Chris Lattner36d3e322009-02-21 00:46:50 +000010665 // If this load is a load from a GEP with a constant offset from an alloca,
10666 // then we don't want to sink it. In its present form, it will be
10667 // load [constant stack offset]. Sinking it will cause us to have to
10668 // materialize the stack addresses in each predecessor in a register only to
10669 // do a shared load from register in the successor.
10670 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10671 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10672 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10673 return false;
10674
Chris Lattner76c73142006-11-01 07:13:54 +000010675 return true;
10676}
10677
Chris Lattner9fe38862003-06-19 17:00:31 +000010678
Chris Lattnerbac32862004-11-14 19:13:23 +000010679// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10680// operator and they all are only used by the PHI, PHI together their
10681// inputs, and do the operation once, to the result of the PHI.
10682Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10683 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10684
10685 // Scan the instruction, looking for input operations that can be folded away.
10686 // If all input operands to the phi are the same instruction (e.g. a cast from
10687 // the same type or "+42") we can pull the operation through the PHI, reducing
10688 // code size and simplifying code.
10689 Constant *ConstantOp = 0;
10690 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010691 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010692 if (isa<CastInst>(FirstInst)) {
10693 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010694 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010695 // Can fold binop, compare or shift here if the RHS is a constant,
10696 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010697 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010698 if (ConstantOp == 0)
10699 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010700 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10701 isVolatile = LI->isVolatile();
10702 // We can't sink the load if the loaded value could be modified between the
10703 // load and the PHI.
10704 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010705 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010706 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010707
10708 // If the PHI is of volatile loads and the load block has multiple
10709 // successors, sinking it would remove a load of the volatile value from
10710 // the path through the other successor.
10711 if (isVolatile &&
10712 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10713 return 0;
10714
Chris Lattner9c080502006-11-01 07:43:41 +000010715 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010716 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010717 } else {
10718 return 0; // Cannot fold this operation.
10719 }
10720
10721 // Check to see if all arguments are the same operation.
10722 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10723 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10724 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010725 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010726 return 0;
10727 if (CastSrcTy) {
10728 if (I->getOperand(0)->getType() != CastSrcTy)
10729 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010730 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010731 // We can't sink the load if the loaded value could be modified between
10732 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010733 if (LI->isVolatile() != isVolatile ||
10734 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010735 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010736 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010737
Chris Lattner71042962008-07-08 17:18:32 +000010738 // If the PHI is of volatile loads and the load block has multiple
10739 // successors, sinking it would remove a load of the volatile value from
10740 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010741 if (isVolatile &&
10742 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10743 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010744
Chris Lattnerbac32862004-11-14 19:13:23 +000010745 } else if (I->getOperand(1) != ConstantOp) {
10746 return 0;
10747 }
10748 }
10749
10750 // Okay, they are all the same operation. Create a new PHI node of the
10751 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010752 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10753 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010754 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010755
10756 Value *InVal = FirstInst->getOperand(0);
10757 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010758
10759 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010760 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10761 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10762 if (NewInVal != InVal)
10763 InVal = 0;
10764 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10765 }
10766
10767 Value *PhiVal;
10768 if (InVal) {
10769 // The new PHI unions all of the same values together. This is really
10770 // common, so we handle it intelligently here for compile-time speed.
10771 PhiVal = InVal;
10772 delete NewPN;
10773 } else {
10774 InsertNewInstBefore(NewPN, PN);
10775 PhiVal = NewPN;
10776 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010777
Chris Lattnerbac32862004-11-14 19:13:23 +000010778 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010779 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010780 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010781 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010782 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010783 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Owen Anderson333c4002009-07-09 23:48:35 +000010784 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010785 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010786 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10787
10788 // If this was a volatile load that we are merging, make sure to loop through
10789 // and mark all the input loads as non-volatile. If we don't do this, we will
10790 // insert a new volatile load and the old ones will not be deletable.
10791 if (isVolatile)
10792 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10793 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10794
10795 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010796}
Chris Lattnera1be5662002-05-02 17:06:02 +000010797
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010798/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10799/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010800static bool DeadPHICycle(PHINode *PN,
10801 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010802 if (PN->use_empty()) return true;
10803 if (!PN->hasOneUse()) return false;
10804
10805 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010806 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010807 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010808
10809 // Don't scan crazily complex things.
10810 if (PotentiallyDeadPHIs.size() == 16)
10811 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010812
10813 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10814 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010815
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010816 return false;
10817}
10818
Chris Lattnercf5008a2007-11-06 21:52:06 +000010819/// PHIsEqualValue - Return true if this phi node is always equal to
10820/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10821/// z = some value; x = phi (y, z); y = phi (x, z)
10822static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10823 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10824 // See if we already saw this PHI node.
10825 if (!ValueEqualPHIs.insert(PN))
10826 return true;
10827
10828 // Don't scan crazily complex things.
10829 if (ValueEqualPHIs.size() == 16)
10830 return false;
10831
10832 // Scan the operands to see if they are either phi nodes or are equal to
10833 // the value.
10834 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10835 Value *Op = PN->getIncomingValue(i);
10836 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10837 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10838 return false;
10839 } else if (Op != NonPhiInVal)
10840 return false;
10841 }
10842
10843 return true;
10844}
10845
10846
Chris Lattner473945d2002-05-06 18:06:38 +000010847// PHINode simplification
10848//
Chris Lattner7e708292002-06-25 16:13:24 +000010849Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010850 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010851 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010852
Owen Anderson7e057142006-07-10 22:03:18 +000010853 if (Value *V = PN.hasConstantValue())
10854 return ReplaceInstUsesWith(PN, V);
10855
Owen Anderson7e057142006-07-10 22:03:18 +000010856 // If all PHI operands are the same operation, pull them through the PHI,
10857 // reducing code size.
10858 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010859 isa<Instruction>(PN.getIncomingValue(1)) &&
10860 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10861 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10862 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10863 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010864 PN.getIncomingValue(0)->hasOneUse())
10865 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10866 return Result;
10867
10868 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10869 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10870 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010871 if (PN.hasOneUse()) {
10872 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10873 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010874 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010875 PotentiallyDeadPHIs.insert(&PN);
10876 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersond672ecb2009-07-03 00:17:18 +000010877 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010878 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010879
10880 // If this phi has a single use, and if that use just computes a value for
10881 // the next iteration of a loop, delete the phi. This occurs with unused
10882 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10883 // common case here is good because the only other things that catch this
10884 // are induction variable analysis (sometimes) and ADCE, which is only run
10885 // late.
10886 if (PHIUser->hasOneUse() &&
10887 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10888 PHIUser->use_back() == &PN) {
Owen Andersond672ecb2009-07-03 00:17:18 +000010889 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010890 }
10891 }
Owen Anderson7e057142006-07-10 22:03:18 +000010892
Chris Lattnercf5008a2007-11-06 21:52:06 +000010893 // We sometimes end up with phi cycles that non-obviously end up being the
10894 // same value, for example:
10895 // z = some value; x = phi (y, z); y = phi (x, z)
10896 // where the phi nodes don't necessarily need to be in the same block. Do a
10897 // quick check to see if the PHI node only contains a single non-phi value, if
10898 // so, scan to see if the phi cycle is actually equal to that value.
10899 {
10900 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10901 // Scan for the first non-phi operand.
10902 while (InValNo != NumOperandVals &&
10903 isa<PHINode>(PN.getIncomingValue(InValNo)))
10904 ++InValNo;
10905
10906 if (InValNo != NumOperandVals) {
10907 Value *NonPhiInVal = PN.getOperand(InValNo);
10908
10909 // Scan the rest of the operands to see if there are any conflicts, if so
10910 // there is no need to recursively scan other phis.
10911 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10912 Value *OpVal = PN.getIncomingValue(InValNo);
10913 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10914 break;
10915 }
10916
10917 // If we scanned over all operands, then we have one unique value plus
10918 // phi values. Scan PHI nodes to see if they all merge in each other or
10919 // the value.
10920 if (InValNo == NumOperandVals) {
10921 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10922 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10923 return ReplaceInstUsesWith(PN, NonPhiInVal);
10924 }
10925 }
10926 }
Chris Lattner60921c92003-12-19 05:58:40 +000010927 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010928}
10929
Reid Spencer17212df2006-12-12 09:18:51 +000010930static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10931 Instruction *InsertPoint,
10932 InstCombiner *IC) {
Dan Gohman6de29f82009-06-15 22:12:54 +000010933 unsigned PtrSize = DTy->getScalarSizeInBits();
10934 unsigned VTySize = V->getType()->getScalarSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010935 // We must cast correctly to the pointer type. Ensure that we
10936 // sign extend the integer value if it is smaller as this is
10937 // used for address computation.
10938 Instruction::CastOps opcode =
10939 (VTySize < PtrSize ? Instruction::SExt :
10940 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10941 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010942}
10943
Chris Lattnera1be5662002-05-02 17:06:02 +000010944
Chris Lattner7e708292002-06-25 16:13:24 +000010945Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010946 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010947 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010948 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010949 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010950 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010951
Chris Lattnere87597f2004-10-16 18:11:37 +000010952 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000010953 return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010954
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010955 bool HasZeroPointerIndex = false;
10956 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10957 HasZeroPointerIndex = C->isNullValue();
10958
10959 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010960 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010961
Chris Lattner28977af2004-04-05 01:30:19 +000010962 // Eliminate unneeded casts for indices.
10963 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010964
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010965 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010966 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10967 i != e; ++i, ++GTI) {
Sanjiv Gupta7787d4a2009-04-24 02:37:54 +000010968 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010969 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010970 if (CI->getOpcode() == Instruction::ZExt ||
10971 CI->getOpcode() == Instruction::SExt) {
10972 const Type *SrcTy = CI->getOperand(0)->getType();
10973 // We can eliminate a cast from i32 to i64 iff the target
10974 // is a 32-bit pointer target.
Dan Gohman6de29f82009-06-15 22:12:54 +000010975 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010976 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000010977 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000010978 }
10979 }
10980 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010981 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000010982 // to what we need. If narrower, sign-extend it to what we need.
10983 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010984 // insert it. This explicit cast can make subsequent optimizations more
10985 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000010986 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010987 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010988 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000010989 *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000010990 MadeChange = true;
10991 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010992 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10993 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010994 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010995 MadeChange = true;
10996 }
Dan Gohman4f833d42008-09-11 23:06:38 +000010997 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10998 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000010999 *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
Dan Gohman4f833d42008-09-11 23:06:38 +000011000 MadeChange = true;
11001 } else {
11002 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11003 GEP);
11004 *i = Op;
11005 MadeChange = true;
11006 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011007 }
Chris Lattner28977af2004-04-05 01:30:19 +000011008 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011009 }
Chris Lattner28977af2004-04-05 01:30:19 +000011010 if (MadeChange) return &GEP;
11011
Chris Lattner90ac28c2002-08-02 19:29:35 +000011012 // Combine Indices - If the source pointer to this getelementptr instruction
11013 // is a getelementptr instruction, combine the indices of the two
11014 // getelementptr instructions into a single instruction.
11015 //
Chris Lattner72588fc2007-02-15 22:48:32 +000011016 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000011017 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000011018 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000011019
11020 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000011021 // Note that if our source is a gep chain itself that we wait for that
11022 // chain to be resolved before we perform this transformation. This
11023 // avoids us creating a TON of code in some cases.
11024 //
11025 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11026 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11027 return 0; // Wait until our source is folded to completion.
11028
Chris Lattner72588fc2007-02-15 22:48:32 +000011029 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011030
11031 // Find out whether the last index in the source GEP is a sequential idx.
11032 bool EndsWithSequential = false;
11033 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11034 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011035 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011036
Chris Lattner90ac28c2002-08-02 19:29:35 +000011037 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011038 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011039 // Replace: gep (gep %P, long B), long A, ...
11040 // With: T = long A+B; gep %P, T, ...
11041 //
Chris Lattner620ce142004-05-07 22:09:22 +000011042 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011043 if (SO1 == Context->getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011044 Sum = GO1;
Owen Andersond672ecb2009-07-03 00:17:18 +000011045 } else if (GO1 == Context->getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011046 Sum = SO1;
11047 } else {
11048 // If they aren't the same type, convert both to an integer of the
11049 // target's pointer size.
11050 if (SO1->getType() != GO1->getType()) {
11051 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011052 SO1 =
11053 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011054 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011055 GO1 =
11056 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011057 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000011058 unsigned PS = TD->getPointerSizeInBits();
11059 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011060 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011061 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011062
Duncan Sands514ab342007-11-01 20:53:16 +000011063 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011064 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011065 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011066 } else {
11067 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000011068 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11069 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011070 }
11071 }
11072 }
Chris Lattner620ce142004-05-07 22:09:22 +000011073 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Andersond672ecb2009-07-03 00:17:18 +000011074 Sum = Context->getConstantExprAdd(cast<Constant>(SO1),
11075 cast<Constant>(GO1));
Chris Lattner620ce142004-05-07 22:09:22 +000011076 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011077 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011078 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011079 }
Chris Lattner28977af2004-04-05 01:30:19 +000011080 }
Chris Lattner620ce142004-05-07 22:09:22 +000011081
11082 // Recycle the GEP we already have if possible.
11083 if (SrcGEPOperands.size() == 2) {
11084 GEP.setOperand(0, SrcGEPOperands[0]);
11085 GEP.setOperand(1, Sum);
11086 return &GEP;
11087 } else {
11088 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11089 SrcGEPOperands.end()-1);
11090 Indices.push_back(Sum);
11091 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11092 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011093 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011094 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000011095 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011096 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000011097 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11098 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011099 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11100 }
11101
11102 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000011103 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11104 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000011105
Chris Lattner620ce142004-05-07 22:09:22 +000011106 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000011107 // GEP of global variable. If all of the indices for this GEP are
11108 // constants, we can promote this to a constexpr instead of an instruction.
11109
11110 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000011111 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000011112 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11113 for (; I != E && isa<Constant>(*I); ++I)
11114 Indices.push_back(cast<Constant>(*I));
11115
11116 if (I == E) { // If they are all constants...
Owen Andersond672ecb2009-07-03 00:17:18 +000011117 Constant *CE = Context->getConstantExprGetElementPtr(GV,
Chris Lattner55eb1c42007-01-31 04:40:53 +000011118 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000011119
11120 // Replace all uses of the GEP with the new constexpr...
11121 return ReplaceInstUsesWith(GEP, CE);
11122 }
Reid Spencer3da59db2006-11-27 01:05:10 +000011123 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000011124 if (!isa<PointerType>(X->getType())) {
11125 // Not interesting. Source pointer must be a cast from pointer.
11126 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011127 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11128 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011129 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011130 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11131 // into : GEP i8* X, ...
11132 //
Chris Lattnereed48272005-09-13 00:40:14 +000011133 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011134 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11135 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011136 if (const ArrayType *CATy =
11137 dyn_cast<ArrayType>(CPTy->getElementType())) {
11138 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11139 if (CATy->getElementType() == XTy->getElementType()) {
11140 // -> GEP i8* X, ...
11141 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11142 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11143 GEP.getName());
11144 } else if (const ArrayType *XATy =
11145 dyn_cast<ArrayType>(XTy->getElementType())) {
11146 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011147 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011148 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011149 // At this point, we know that the cast source type is a pointer
11150 // to an array of the same type as the destination pointer
11151 // array. Because the array type is never stepped over (there
11152 // is a leading zero) we can fold the cast into this GEP.
11153 GEP.setOperand(0, X);
11154 return &GEP;
11155 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011156 }
11157 }
Chris Lattnereed48272005-09-13 00:40:14 +000011158 } else if (GEP.getNumOperands() == 2) {
11159 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011160 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11161 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011162 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11163 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11164 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011165 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11166 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011167 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011168 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011169 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000011170 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000011171 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011172 // V and GEP are both pointer types --> BitCast
11173 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011174 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011175
11176 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011177 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011178 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011179 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011180
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011181 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011182 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011183 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011184
11185 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11186 // allow either a mul, shift, or constant here.
11187 Value *NewIdx = 0;
11188 ConstantInt *Scale = 0;
11189 if (ArrayEltSize == 1) {
11190 NewIdx = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011191 Scale =
11192 Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011193 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011194 NewIdx = Context->getConstantInt(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011195 Scale = CI;
11196 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11197 if (Inst->getOpcode() == Instruction::Shl &&
11198 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011199 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11200 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersond672ecb2009-07-03 00:17:18 +000011201 Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011202 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011203 NewIdx = Inst->getOperand(0);
11204 } else if (Inst->getOpcode() == Instruction::Mul &&
11205 isa<ConstantInt>(Inst->getOperand(1))) {
11206 Scale = cast<ConstantInt>(Inst->getOperand(1));
11207 NewIdx = Inst->getOperand(0);
11208 }
11209 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011210
Chris Lattner7835cdd2005-09-13 18:36:04 +000011211 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011212 // out, perform the transformation. Note, we don't know whether Scale is
11213 // signed or not. We'll use unsigned version of division/modulo
11214 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011215 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011216 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011217 Scale = Context->getConstantInt(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011218 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011219 if (Scale->getZExtValue() != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011220 Constant *C =
11221 Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011222 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011223 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011224 NewIdx = InsertNewInstBefore(Sc, GEP);
11225 }
11226
11227 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011228 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011229 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011230 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011231 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011232 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011233 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11234 // The NewGEP must be pointer typed, so must the old one -> BitCast
11235 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011236 }
11237 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011238 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011239 }
Chris Lattner58407792009-01-09 04:53:57 +000011240
Chris Lattner46cd5a12009-01-09 05:44:56 +000011241 /// See if we can simplify:
11242 /// X = bitcast A to B*
11243 /// Y = gep X, <...constant indices...>
11244 /// into a gep of the original struct. This is important for SROA and alias
11245 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011246 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011247 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11248 // Determine how much the GEP moves the pointer. We are guaranteed to get
11249 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011250 ConstantInt *OffsetV =
11251 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011252 int64_t Offset = OffsetV->getSExtValue();
11253
11254 // If this GEP instruction doesn't move the pointer, just replace the GEP
11255 // with a bitcast of the real input to the dest type.
11256 if (Offset == 0) {
11257 // If the bitcast is of an allocation, and the allocation will be
11258 // converted to match the type of the cast, don't touch this.
11259 if (isa<AllocationInst>(BCI->getOperand(0))) {
11260 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11261 if (Instruction *I = visitBitCast(*BCI)) {
11262 if (I != BCI) {
11263 I->takeName(BCI);
11264 BCI->getParent()->getInstList().insert(BCI, I);
11265 ReplaceInstUsesWith(*BCI, I);
11266 }
11267 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011268 }
Chris Lattner58407792009-01-09 04:53:57 +000011269 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011270 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011271 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011272
11273 // Otherwise, if the offset is non-zero, we need to find out if there is a
11274 // field at Offset in 'A's type. If so, we can pull the cast through the
11275 // GEP.
11276 SmallVector<Value*, 8> NewIndices;
11277 const Type *InTy =
11278 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011279 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011280 Instruction *NGEP =
11281 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11282 NewIndices.end());
11283 if (NGEP->getType() == GEP.getType()) return NGEP;
11284 InsertNewInstBefore(NGEP, GEP);
11285 NGEP->takeName(&GEP);
11286 return new BitCastInst(NGEP, GEP.getType());
11287 }
Chris Lattner58407792009-01-09 04:53:57 +000011288 }
11289 }
11290
Chris Lattner8a2a3112001-12-14 16:52:21 +000011291 return 0;
11292}
11293
Chris Lattner0864acf2002-11-04 16:18:53 +000011294Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11295 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011296 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011297 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11298 const Type *NewTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000011299 Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011300 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011301
11302 // Create and insert the replacement instruction...
11303 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +000011304 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011305 else {
11306 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Owen Anderson50dead02009-07-15 23:53:25 +000011307 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011308 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011309
11310 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011311
Chris Lattner0864acf2002-11-04 16:18:53 +000011312 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011313 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011314 //
11315 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011316 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011317
11318 // Now that I is pointing to the first non-allocation-inst in the block,
11319 // insert our getelementptr instruction...
11320 //
Owen Andersond672ecb2009-07-03 00:17:18 +000011321 Value *NullIdx = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011322 Value *Idx[2];
11323 Idx[0] = NullIdx;
11324 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011325 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11326 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011327
11328 // Now make everything use the getelementptr instead of the original
11329 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011330 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011331 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011332 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011333 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011334 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011335
Dan Gohman6893cd72009-01-13 20:18:38 +000011336 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11337 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011338 // Note that we only do this for alloca's, because malloc should allocate
11339 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011340 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersond672ecb2009-07-03 00:17:18 +000011341 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011342
11343 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11344 if (AI.getAlignment() == 0)
11345 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11346 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011347
Chris Lattner0864acf2002-11-04 16:18:53 +000011348 return 0;
11349}
11350
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011351Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11352 Value *Op = FI.getOperand(0);
11353
Chris Lattner17be6352004-10-18 02:59:09 +000011354 // free undef -> unreachable.
11355 if (isa<UndefValue>(Op)) {
11356 // Insert a new store to null because we cannot modify the CFG here.
Owen Andersonb3056fa2009-07-21 18:03:38 +000011357 new StoreInst(Context->getTrue(),
Owen Andersond672ecb2009-07-03 00:17:18 +000011358 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011359 return EraseInstFromFunction(FI);
11360 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011361
Chris Lattner6160e852004-02-28 04:57:37 +000011362 // If we have 'free null' delete the instruction. This can happen in stl code
11363 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011364 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011365 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011366
11367 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11368 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11369 FI.setOperand(0, CI->getOperand(0));
11370 return &FI;
11371 }
11372
11373 // Change free (gep X, 0,0,0,0) into free(X)
11374 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11375 if (GEPI->hasAllZeroIndices()) {
11376 AddToWorkList(GEPI);
11377 FI.setOperand(0, GEPI->getOperand(0));
11378 return &FI;
11379 }
11380 }
11381
11382 // Change free(malloc) into nothing, if the malloc has a single use.
11383 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11384 if (MI->hasOneUse()) {
11385 EraseInstFromFunction(FI);
11386 return EraseInstFromFunction(*MI);
11387 }
Chris Lattner6160e852004-02-28 04:57:37 +000011388
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011389 return 0;
11390}
11391
11392
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011393/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011394static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011395 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011396 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011397 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011398 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011399
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011400 if (TD) {
11401 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11402 // Instead of loading constant c string, use corresponding integer value
11403 // directly if string length is small enough.
11404 std::string Str;
11405 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11406 unsigned len = Str.length();
11407 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11408 unsigned numBits = Ty->getPrimitiveSizeInBits();
11409 // Replace LI with immediate integer store.
11410 if ((numBits >> 3) == len + 1) {
11411 APInt StrVal(numBits, 0);
11412 APInt SingleChar(numBits, 0);
11413 if (TD->isLittleEndian()) {
11414 for (signed i = len-1; i >= 0; i--) {
11415 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11416 StrVal = (StrVal << 8) | SingleChar;
11417 }
11418 } else {
11419 for (unsigned i = 0; i < len; i++) {
11420 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11421 StrVal = (StrVal << 8) | SingleChar;
11422 }
11423 // Append NULL at the end.
11424 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011425 StrVal = (StrVal << 8) | SingleChar;
11426 }
Owen Andersond672ecb2009-07-03 00:17:18 +000011427 Value *NL = Context->getConstantInt(StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011428 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011429 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011430 }
11431 }
11432 }
11433
Mon P Wang6753f952009-02-07 22:19:29 +000011434 const PointerType *DestTy = cast<PointerType>(CI->getType());
11435 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011436 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011437
11438 // If the address spaces don't match, don't eliminate the cast.
11439 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11440 return 0;
11441
Chris Lattnerb89e0712004-07-13 01:49:43 +000011442 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011443
Reid Spencer42230162007-01-22 05:51:25 +000011444 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011445 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011446 // If the source is an array, the code below will not succeed. Check to
11447 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11448 // constants.
11449 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11450 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11451 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011452 Value *Idxs[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011453 Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11454 CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011455 SrcTy = cast<PointerType>(CastOp->getType());
11456 SrcPTy = SrcTy->getElementType();
11457 }
11458
Reid Spencer42230162007-01-22 05:51:25 +000011459 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011460 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011461 // Do not allow turning this into a load of an integer, which is then
11462 // casted to a pointer, this pessimizes pointer analysis a lot.
11463 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000011464 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11465 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011466
Chris Lattnerf9527852005-01-31 04:50:46 +000011467 // Okay, we are casting from one integer or pointer type to another of
11468 // the same size. Instead of casting the pointer before the load, cast
11469 // the result of the loaded value.
11470 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11471 CI->getName(),
11472 LI.isVolatile()),LI);
11473 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011474 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011475 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011476 }
11477 }
11478 return 0;
11479}
11480
Chris Lattner833b8a42003-06-26 05:06:25 +000011481Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11482 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011483
Dan Gohman9941f742007-07-20 16:34:21 +000011484 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011485 unsigned KnownAlign =
11486 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011487 if (KnownAlign >
11488 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11489 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011490 LI.setAlignment(KnownAlign);
11491
Chris Lattner37366c12005-05-01 04:24:53 +000011492 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011493 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011494 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011495 return Res;
11496
11497 // None of the following transforms are legal for volatile loads.
11498 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011499
Dan Gohman2276a7b2008-10-15 23:19:35 +000011500 // Do really simple store-to-load forwarding and load CSE, to catch cases
11501 // where there are several consequtive memory accesses to the same location,
11502 // separated by a few arithmetic operations.
11503 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011504 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11505 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011506
Christopher Lambb15147e2007-12-29 07:56:53 +000011507 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11508 const Value *GEPI0 = GEPI->getOperand(0);
11509 // TODO: Consider a target hook for valid address spaces for this xform.
11510 if (isa<ConstantPointerNull>(GEPI0) &&
11511 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011512 // Insert a new store to null instruction before the load to indicate
11513 // that this code is not reachable. We do this instead of inserting
11514 // an unreachable instruction directly because we cannot modify the
11515 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011516 new StoreInst(Context->getUndef(LI.getType()),
11517 Context->getNullValue(Op->getType()), &LI);
11518 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011519 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011520 }
Chris Lattner37366c12005-05-01 04:24:53 +000011521
Chris Lattnere87597f2004-10-16 18:11:37 +000011522 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011523 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011524 // TODO: Consider a target hook for valid address spaces for this xform.
11525 if (isa<UndefValue>(C) || (C->isNullValue() &&
11526 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011527 // Insert a new store to null instruction before the load to indicate that
11528 // this code is not reachable. We do this instead of inserting an
11529 // unreachable instruction directly because we cannot modify the CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011530 new StoreInst(Context->getUndef(LI.getType()),
11531 Context->getNullValue(Op->getType()), &LI);
11532 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011533 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011534
Chris Lattnere87597f2004-10-16 18:11:37 +000011535 // Instcombine load (constant global) into the value loaded.
11536 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011537 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011538 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011539
Chris Lattnere87597f2004-10-16 18:11:37 +000011540 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011541 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011542 if (CE->getOpcode() == Instruction::GetElementPtr) {
11543 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011544 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011545 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011546 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
11547 Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011548 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011549 if (CE->getOperand(0)->isNullValue()) {
11550 // Insert a new store to null instruction before the load to indicate
11551 // that this code is not reachable. We do this instead of inserting
11552 // an unreachable instruction directly because we cannot modify the
11553 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011554 new StoreInst(Context->getUndef(LI.getType()),
11555 Context->getNullValue(Op->getType()), &LI);
11556 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011557 }
11558
Reid Spencer3da59db2006-11-27 01:05:10 +000011559 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011560 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011561 return Res;
11562 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011563 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011564 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011565
11566 // If this load comes from anywhere in a constant global, and if the global
11567 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011568 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011569 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011570 if (GV->getInitializer()->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +000011571 return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011572 else if (isa<UndefValue>(GV->getInitializer()))
Owen Andersond672ecb2009-07-03 00:17:18 +000011573 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011574 }
11575 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011576
Chris Lattner37366c12005-05-01 04:24:53 +000011577 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011578 // Change select and PHI nodes to select values instead of addresses: this
11579 // helps alias analysis out a lot, allows many others simplifications, and
11580 // exposes redundancy in the code.
11581 //
11582 // Note that we cannot do the transformation unless we know that the
11583 // introduced loads cannot trap! Something like this is valid as long as
11584 // the condition is always false: load (select bool %C, int* null, int* %G),
11585 // but it would not be valid if we transformed it to load from null
11586 // unconditionally.
11587 //
11588 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11589 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011590 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11591 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011592 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011593 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011594 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011595 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011596 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011597 }
11598
Chris Lattner684fe212004-09-23 15:46:00 +000011599 // load (select (cond, null, P)) -> load P
11600 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11601 if (C->isNullValue()) {
11602 LI.setOperand(0, SI->getOperand(2));
11603 return &LI;
11604 }
11605
11606 // load (select (cond, P, null)) -> load P
11607 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11608 if (C->isNullValue()) {
11609 LI.setOperand(0, SI->getOperand(1));
11610 return &LI;
11611 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011612 }
11613 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011614 return 0;
11615}
11616
Reid Spencer55af2b52007-01-19 21:20:31 +000011617/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011618/// when possible. This makes it generally easy to do alias analysis and/or
11619/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011620static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11621 User *CI = cast<User>(SI.getOperand(1));
11622 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011623 LLVMContext *Context = IC.getContext();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011624
11625 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011626 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11627 if (SrcTy == 0) return 0;
11628
11629 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011630
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011631 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11632 return 0;
11633
Chris Lattner3914f722009-01-24 01:00:13 +000011634 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11635 /// to its first element. This allows us to handle things like:
11636 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11637 /// on 32-bit hosts.
11638 SmallVector<Value*, 4> NewGEPIndices;
11639
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011640 // If the source is an array, the code below will not succeed. Check to
11641 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11642 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011643 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11644 // Index through pointer.
Owen Andersond672ecb2009-07-03 00:17:18 +000011645 Constant *Zero = Context->getNullValue(Type::Int32Ty);
Chris Lattner3914f722009-01-24 01:00:13 +000011646 NewGEPIndices.push_back(Zero);
11647
11648 while (1) {
11649 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011650 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011651 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011652 NewGEPIndices.push_back(Zero);
11653 SrcPTy = STy->getElementType(0);
11654 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11655 NewGEPIndices.push_back(Zero);
11656 SrcPTy = ATy->getElementType();
11657 } else {
11658 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011659 }
Chris Lattner3914f722009-01-24 01:00:13 +000011660 }
11661
Owen Andersond672ecb2009-07-03 00:17:18 +000011662 SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011663 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011664
11665 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11666 return 0;
11667
Chris Lattner71759c42009-01-16 20:12:52 +000011668 // If the pointers point into different address spaces or if they point to
11669 // values with different sizes, we can't do the transformation.
11670 if (SrcTy->getAddressSpace() !=
11671 cast<PointerType>(CI->getType())->getAddressSpace() ||
11672 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011673 IC.getTargetData().getTypeSizeInBits(DestPTy))
11674 return 0;
11675
11676 // Okay, we are casting from one integer or pointer type to another of
11677 // the same size. Instead of casting the pointer before
11678 // the store, cast the value to be stored.
11679 Value *NewCast;
11680 Value *SIOp0 = SI.getOperand(0);
11681 Instruction::CastOps opcode = Instruction::BitCast;
11682 const Type* CastSrcTy = SIOp0->getType();
11683 const Type* CastDstTy = SrcPTy;
11684 if (isa<PointerType>(CastDstTy)) {
11685 if (CastSrcTy->isInteger())
11686 opcode = Instruction::IntToPtr;
11687 } else if (isa<IntegerType>(CastDstTy)) {
11688 if (isa<PointerType>(SIOp0->getType()))
11689 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011690 }
Chris Lattner3914f722009-01-24 01:00:13 +000011691
11692 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11693 // emit a GEP to index into its first field.
11694 if (!NewGEPIndices.empty()) {
11695 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000011696 CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner3914f722009-01-24 01:00:13 +000011697 NewGEPIndices.size());
11698 else
11699 CastOp = IC.InsertNewInstBefore(
11700 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11701 NewGEPIndices.end()), SI);
11702 }
11703
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011704 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Andersond672ecb2009-07-03 00:17:18 +000011705 NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011706 else
11707 NewCast = IC.InsertNewInstBefore(
11708 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11709 SI);
11710 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011711}
11712
Chris Lattner4aebaee2008-11-27 08:56:30 +000011713/// equivalentAddressValues - Test if A and B will obviously have the same
11714/// value. This includes recognizing that %t0 and %t1 will have the same
11715/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011716/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011717/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011718/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011719/// %t2 = load i32* %t1
11720///
11721static bool equivalentAddressValues(Value *A, Value *B) {
11722 // Test if the values are trivially equivalent.
11723 if (A == B) return true;
11724
11725 // Test if the values come form identical arithmetic instructions.
11726 if (isa<BinaryOperator>(A) ||
11727 isa<CastInst>(A) ||
11728 isa<PHINode>(A) ||
11729 isa<GetElementPtrInst>(A))
11730 if (Instruction *BI = dyn_cast<Instruction>(B))
11731 if (cast<Instruction>(A)->isIdenticalTo(BI))
11732 return true;
11733
11734 // Otherwise they may not be equivalent.
11735 return false;
11736}
11737
Dale Johannesen4945c652009-03-03 21:26:39 +000011738// If this instruction has two uses, one of which is a llvm.dbg.declare,
11739// return the llvm.dbg.declare.
11740DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11741 if (!V->hasNUses(2))
11742 return 0;
11743 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11744 UI != E; ++UI) {
11745 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11746 return DI;
11747 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11748 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11749 return DI;
11750 }
11751 }
11752 return 0;
11753}
11754
Chris Lattner2f503e62005-01-31 05:36:43 +000011755Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11756 Value *Val = SI.getOperand(0);
11757 Value *Ptr = SI.getOperand(1);
11758
11759 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011760 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011761 ++NumCombined;
11762 return 0;
11763 }
Chris Lattner836692d2007-01-15 06:51:56 +000011764
11765 // If the RHS is an alloca with a single use, zapify the store, making the
11766 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011767 // If the RHS is an alloca with a two uses, the other one being a
11768 // llvm.dbg.declare, zapify the store and the declare, making the
11769 // alloca dead. We must do this to prevent declare's from affecting
11770 // codegen.
11771 if (!SI.isVolatile()) {
11772 if (Ptr->hasOneUse()) {
11773 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011774 EraseInstFromFunction(SI);
11775 ++NumCombined;
11776 return 0;
11777 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011778 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11779 if (isa<AllocaInst>(GEP->getOperand(0))) {
11780 if (GEP->getOperand(0)->hasOneUse()) {
11781 EraseInstFromFunction(SI);
11782 ++NumCombined;
11783 return 0;
11784 }
11785 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11786 EraseInstFromFunction(*DI);
11787 EraseInstFromFunction(SI);
11788 ++NumCombined;
11789 return 0;
11790 }
11791 }
11792 }
11793 }
11794 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11795 EraseInstFromFunction(*DI);
11796 EraseInstFromFunction(SI);
11797 ++NumCombined;
11798 return 0;
11799 }
Chris Lattner836692d2007-01-15 06:51:56 +000011800 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011801
Dan Gohman9941f742007-07-20 16:34:21 +000011802 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011803 unsigned KnownAlign =
11804 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011805 if (KnownAlign >
11806 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11807 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011808 SI.setAlignment(KnownAlign);
11809
Dale Johannesenacb51a32009-03-03 01:43:03 +000011810 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011811 // stores to the same location, separated by a few arithmetic operations. This
11812 // situation often occurs with bitfield accesses.
11813 BasicBlock::iterator BBI = &SI;
11814 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11815 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011816 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011817 // Don't count debug info directives, lest they affect codegen,
11818 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11819 // It is necessary for correctness to skip those that feed into a
11820 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011821 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011822 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011823 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011824 continue;
11825 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011826
11827 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11828 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011829 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11830 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011831 ++NumDeadStore;
11832 ++BBI;
11833 EraseInstFromFunction(*PrevSI);
11834 continue;
11835 }
11836 break;
11837 }
11838
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011839 // If this is a load, we have to stop. However, if the loaded value is from
11840 // the pointer we're loading and is producing the pointer we're storing,
11841 // then *this* store is dead (X = load P; store X -> P).
11842 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011843 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11844 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011845 EraseInstFromFunction(SI);
11846 ++NumCombined;
11847 return 0;
11848 }
11849 // Otherwise, this is a load from some other location. Stores before it
11850 // may not be dead.
11851 break;
11852 }
11853
Chris Lattner9ca96412006-02-08 03:25:32 +000011854 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011855 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011856 break;
11857 }
11858
11859
11860 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011861
11862 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011863 if (isa<ConstantPointerNull>(Ptr) &&
11864 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011865 if (!isa<UndefValue>(Val)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011866 SI.setOperand(0, Context->getUndef(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011867 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011868 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011869 ++NumCombined;
11870 }
11871 return 0; // Do not modify these!
11872 }
11873
11874 // store undef, Ptr -> noop
11875 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011876 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011877 ++NumCombined;
11878 return 0;
11879 }
11880
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011881 // If the pointer destination is a cast, see if we can fold the cast into the
11882 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011883 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011884 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11885 return Res;
11886 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011887 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011888 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11889 return Res;
11890
Chris Lattner408902b2005-09-12 23:23:25 +000011891
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011892 // If this store is the last instruction in the basic block (possibly
11893 // excepting debug info instructions and the pointer bitcasts that feed
11894 // into them), and if the block ends with an unconditional branch, try
11895 // to move it to the successor block.
11896 BBI = &SI;
11897 do {
11898 ++BBI;
11899 } while (isa<DbgInfoIntrinsic>(BBI) ||
11900 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011901 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011902 if (BI->isUnconditional())
11903 if (SimplifyStoreAtEndOfBlock(SI))
11904 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011905
Chris Lattner2f503e62005-01-31 05:36:43 +000011906 return 0;
11907}
11908
Chris Lattner3284d1f2007-04-15 00:07:55 +000011909/// SimplifyStoreAtEndOfBlock - Turn things like:
11910/// if () { *P = v1; } else { *P = v2 }
11911/// into a phi node with a store in the successor.
11912///
Chris Lattner31755a02007-04-15 01:02:18 +000011913/// Simplify things like:
11914/// *P = v1; if () { *P = v2; }
11915/// into a phi node with a store in the successor.
11916///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011917bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11918 BasicBlock *StoreBB = SI.getParent();
11919
11920 // Check to see if the successor block has exactly two incoming edges. If
11921 // so, see if the other predecessor contains a store to the same location.
11922 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011923 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011924
11925 // Determine whether Dest has exactly two predecessors and, if so, compute
11926 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011927 pred_iterator PI = pred_begin(DestBB);
11928 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011929 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011930 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011931 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011932 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011933 return false;
11934
11935 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011936 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011937 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011938 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011939 }
Chris Lattner31755a02007-04-15 01:02:18 +000011940 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011941 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011942
11943 // Bail out if all the relevant blocks aren't distinct (this can happen,
11944 // for example, if SI is in an infinite loop)
11945 if (StoreBB == DestBB || OtherBB == DestBB)
11946 return false;
11947
Chris Lattner31755a02007-04-15 01:02:18 +000011948 // Verify that the other block ends in a branch and is not otherwise empty.
11949 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011950 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011951 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011952 return false;
11953
Chris Lattner31755a02007-04-15 01:02:18 +000011954 // If the other block ends in an unconditional branch, check for the 'if then
11955 // else' case. there is an instruction before the branch.
11956 StoreInst *OtherStore = 0;
11957 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011958 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011959 // Skip over debugging info.
11960 while (isa<DbgInfoIntrinsic>(BBI) ||
11961 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11962 if (BBI==OtherBB->begin())
11963 return false;
11964 --BBI;
11965 }
11966 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011967 OtherStore = dyn_cast<StoreInst>(BBI);
11968 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11969 return false;
11970 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011971 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011972 // destinations is StoreBB, then we have the if/then case.
11973 if (OtherBr->getSuccessor(0) != StoreBB &&
11974 OtherBr->getSuccessor(1) != StoreBB)
11975 return false;
11976
11977 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011978 // if/then triangle. See if there is a store to the same ptr as SI that
11979 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011980 for (;; --BBI) {
11981 // Check to see if we find the matching store.
11982 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11983 if (OtherStore->getOperand(1) != SI.getOperand(1))
11984 return false;
11985 break;
11986 }
Eli Friedman6903a242008-06-13 22:02:12 +000011987 // If we find something that may be using or overwriting the stored
11988 // value, or if we run out of instructions, we can't do the xform.
11989 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011990 BBI == OtherBB->begin())
11991 return false;
11992 }
11993
11994 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011995 // make sure nothing reads or overwrites the stored value in
11996 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011997 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11998 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011999 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012000 return false;
12001 }
12002 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012003
Chris Lattner31755a02007-04-15 01:02:18 +000012004 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012005 Value *MergedVal = OtherStore->getOperand(0);
12006 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012007 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012008 PN->reserveOperandSpace(2);
12009 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012010 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12011 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012012 }
12013
12014 // Advance to a place where it is safe to insert the new store and
12015 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012016 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012017 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12018 OtherStore->isVolatile()), *BBI);
12019
12020 // Nuke the old stores.
12021 EraseInstFromFunction(SI);
12022 EraseInstFromFunction(*OtherStore);
12023 ++NumCombined;
12024 return true;
12025}
12026
Chris Lattner2f503e62005-01-31 05:36:43 +000012027
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012028Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12029 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012030 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012031 BasicBlock *TrueDest;
12032 BasicBlock *FalseDest;
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012033 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012034 !isa<Constant>(X)) {
12035 // Swap Destinations and condition...
12036 BI.setCondition(X);
12037 BI.setSuccessor(0, FalseDest);
12038 BI.setSuccessor(1, TrueDest);
12039 return &BI;
12040 }
12041
Reid Spencere4d87aa2006-12-23 06:05:41 +000012042 // Cannonicalize fcmp_one -> fcmp_oeq
12043 FCmpInst::Predicate FPred; Value *Y;
12044 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012045 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012046 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12047 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12048 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012049 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012050 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012051 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012052 // Swap Destinations and condition...
12053 BI.setCondition(NewSCC);
12054 BI.setSuccessor(0, FalseDest);
12055 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012056 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012057 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012058 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012059 return &BI;
12060 }
12061
12062 // Cannonicalize icmp_ne -> icmp_eq
12063 ICmpInst::Predicate IPred;
12064 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012065 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012066 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12067 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12068 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12069 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012070 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012071 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012072 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000012073 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012074 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012075 BI.setSuccessor(0, FalseDest);
12076 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012077 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012078 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012079 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012080 return &BI;
12081 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012082
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012083 return 0;
12084}
Chris Lattner0864acf2002-11-04 16:18:53 +000012085
Chris Lattner46238a62004-07-03 00:26:11 +000012086Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12087 Value *Cond = SI.getCondition();
12088 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12089 if (I->getOpcode() == Instruction::Add)
12090 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12091 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12092 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012093 SI.setOperand(i,
12094 Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012095 AddRHS));
12096 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000012097 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012098 return &SI;
12099 }
12100 }
12101 return 0;
12102}
12103
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012104Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012105 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012106
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012107 if (!EV.hasIndices())
12108 return ReplaceInstUsesWith(EV, Agg);
12109
12110 if (Constant *C = dyn_cast<Constant>(Agg)) {
12111 if (isa<UndefValue>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012112 return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012113
12114 if (isa<ConstantAggregateZero>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012115 return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012116
12117 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12118 // Extract the element indexed by the first index out of the constant
12119 Value *V = C->getOperand(*EV.idx_begin());
12120 if (EV.getNumIndices() > 1)
12121 // Extract the remaining indices out of the constant indexed by the
12122 // first index
12123 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12124 else
12125 return ReplaceInstUsesWith(EV, V);
12126 }
12127 return 0; // Can't handle other constants
12128 }
12129 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12130 // We're extracting from an insertvalue instruction, compare the indices
12131 const unsigned *exti, *exte, *insi, *inse;
12132 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12133 exte = EV.idx_end(), inse = IV->idx_end();
12134 exti != exte && insi != inse;
12135 ++exti, ++insi) {
12136 if (*insi != *exti)
12137 // The insert and extract both reference distinctly different elements.
12138 // This means the extract is not influenced by the insert, and we can
12139 // replace the aggregate operand of the extract with the aggregate
12140 // operand of the insert. i.e., replace
12141 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12142 // %E = extractvalue { i32, { i32 } } %I, 0
12143 // with
12144 // %E = extractvalue { i32, { i32 } } %A, 0
12145 return ExtractValueInst::Create(IV->getAggregateOperand(),
12146 EV.idx_begin(), EV.idx_end());
12147 }
12148 if (exti == exte && insi == inse)
12149 // Both iterators are at the end: Index lists are identical. Replace
12150 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12151 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12152 // with "i32 42"
12153 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12154 if (exti == exte) {
12155 // The extract list is a prefix of the insert list. i.e. replace
12156 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12157 // %E = extractvalue { i32, { i32 } } %I, 1
12158 // with
12159 // %X = extractvalue { i32, { i32 } } %A, 1
12160 // %E = insertvalue { i32 } %X, i32 42, 0
12161 // by switching the order of the insert and extract (though the
12162 // insertvalue should be left in, since it may have other uses).
12163 Value *NewEV = InsertNewInstBefore(
12164 ExtractValueInst::Create(IV->getAggregateOperand(),
12165 EV.idx_begin(), EV.idx_end()),
12166 EV);
12167 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12168 insi, inse);
12169 }
12170 if (insi == inse)
12171 // The insert list is a prefix of the extract list
12172 // We can simply remove the common indices from the extract and make it
12173 // operate on the inserted value instead of the insertvalue result.
12174 // i.e., replace
12175 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12176 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12177 // with
12178 // %E extractvalue { i32 } { i32 42 }, 0
12179 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12180 exti, exte);
12181 }
12182 // Can't simplify extracts from other values. Note that nested extracts are
12183 // already simplified implicitely by the above (extract ( extract (insert) )
12184 // will be translated into extract ( insert ( extract ) ) first and then just
12185 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012186 return 0;
12187}
12188
Chris Lattner220b0cf2006-03-05 00:22:33 +000012189/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12190/// is to leave as a vector operation.
12191static bool CheapToScalarize(Value *V, bool isConstant) {
12192 if (isa<ConstantAggregateZero>(V))
12193 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012194 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012195 if (isConstant) return true;
12196 // If all elts are the same, we can extract.
12197 Constant *Op0 = C->getOperand(0);
12198 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12199 if (C->getOperand(i) != Op0)
12200 return false;
12201 return true;
12202 }
12203 Instruction *I = dyn_cast<Instruction>(V);
12204 if (!I) return false;
12205
12206 // Insert element gets simplified to the inserted element or is deleted if
12207 // this is constant idx extract element and its a constant idx insertelt.
12208 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12209 isa<ConstantInt>(I->getOperand(2)))
12210 return true;
12211 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12212 return true;
12213 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12214 if (BO->hasOneUse() &&
12215 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12216 CheapToScalarize(BO->getOperand(1), isConstant)))
12217 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012218 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12219 if (CI->hasOneUse() &&
12220 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12221 CheapToScalarize(CI->getOperand(1), isConstant)))
12222 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012223
12224 return false;
12225}
12226
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012227/// Read and decode a shufflevector mask.
12228///
12229/// It turns undef elements into values that are larger than the number of
12230/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012231static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12232 unsigned NElts = SVI->getType()->getNumElements();
12233 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12234 return std::vector<unsigned>(NElts, 0);
12235 if (isa<UndefValue>(SVI->getOperand(2)))
12236 return std::vector<unsigned>(NElts, 2*NElts);
12237
12238 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012239 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012240 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12241 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012242 Result.push_back(NElts*2); // undef -> 8
12243 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012244 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012245 return Result;
12246}
12247
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012248/// FindScalarElement - Given a vector and an element number, see if the scalar
12249/// value is already around as a register, for example if it were inserted then
12250/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012251static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012252 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012253 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12254 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012255 unsigned Width = PTy->getNumElements();
12256 if (EltNo >= Width) // Out of range access.
Owen Andersond672ecb2009-07-03 00:17:18 +000012257 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012258
12259 if (isa<UndefValue>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012260 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012261 else if (isa<ConstantAggregateZero>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012262 return Context->getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012263 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012264 return CP->getOperand(EltNo);
12265 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12266 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012267 if (!isa<ConstantInt>(III->getOperand(2)))
12268 return 0;
12269 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012270
12271 // If this is an insert to the element we are looking for, return the
12272 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012273 if (EltNo == IIElt)
12274 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012275
12276 // Otherwise, the insertelement doesn't modify the value, recurse on its
12277 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012278 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012279 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012280 unsigned LHSWidth =
12281 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012282 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012283 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012284 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012285 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012286 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012287 else
Owen Andersond672ecb2009-07-03 00:17:18 +000012288 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012289 }
12290
12291 // Otherwise, we don't know.
12292 return 0;
12293}
12294
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012295Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012296 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012297 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012298 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012299
Dan Gohman07a96762007-07-16 14:29:03 +000012300 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012301 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012302 return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012303
Reid Spencer9d6565a2007-02-15 02:26:10 +000012304 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012305 // If vector val is constant with all elements the same, replace EI with
12306 // that element. When the elements are not identical, we cannot replace yet
12307 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012308 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012309 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012310 if (C->getOperand(i) != op0) {
12311 op0 = 0;
12312 break;
12313 }
12314 if (op0)
12315 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012316 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012317
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012318 // If extracting a specified index from the vector, see if we can recursively
12319 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012320 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012321 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedman76e7ba82009-07-18 19:04:16 +000012322 unsigned VectorWidth =
12323 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012324
12325 // If this is extracting an invalid index, turn this into undef, to avoid
12326 // crashing the code below.
12327 if (IndexVal >= VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012328 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012329
Chris Lattner867b99f2006-10-05 06:55:50 +000012330 // This instruction only demands the single element from the input vector.
12331 // If the input vector has a single use, simplify it based on this use
12332 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012333 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012334 APInt UndefElts(VectorWidth, 0);
12335 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012336 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012337 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012338 EI.setOperand(0, V);
12339 return &EI;
12340 }
12341 }
12342
Owen Andersond672ecb2009-07-03 00:17:18 +000012343 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012344 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012345
12346 // If the this extractelement is directly using a bitcast from a vector of
12347 // the same number of elements, see if we can find the source element from
12348 // it. In this case, we will end up needing to bitcast the scalars.
12349 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12350 if (const VectorType *VT =
12351 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12352 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012353 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12354 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012355 return new BitCastInst(Elt, EI.getType());
12356 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012357 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012358
Chris Lattner73fa49d2006-05-25 22:53:38 +000012359 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012360 if (I->hasOneUse()) {
12361 // Push extractelement into predecessor operation if legal and
12362 // profitable to do so
12363 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012364 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12365 if (CheapToScalarize(BO, isConstantElt)) {
12366 ExtractElementInst *newEI0 =
12367 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12368 EI.getName()+".lhs");
12369 ExtractElementInst *newEI1 =
12370 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12371 EI.getName()+".rhs");
12372 InsertNewInstBefore(newEI0, EI);
12373 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012374 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012375 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012376 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012377 unsigned AS =
12378 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012379 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +000012380 Context->getPointerType(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012381 GetElementPtrInst *GEP =
12382 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012383 InsertNewInstBefore(GEP, EI);
12384 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012385 }
12386 }
12387 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12388 // Extracting the inserted element?
12389 if (IE->getOperand(2) == EI.getOperand(1))
12390 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12391 // If the inserted and extracted elements are constants, they must not
12392 // be the same value, extract from the pre-inserted value instead.
12393 if (isa<Constant>(IE->getOperand(2)) &&
12394 isa<Constant>(EI.getOperand(1))) {
12395 AddUsesToWorkList(EI);
12396 EI.setOperand(0, IE->getOperand(0));
12397 return &EI;
12398 }
12399 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12400 // If this is extracting an element from a shufflevector, figure out where
12401 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012402 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12403 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012404 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012405 unsigned LHSWidth =
12406 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12407
12408 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012409 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012410 else if (SrcIdx < LHSWidth*2) {
12411 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012412 Src = SVI->getOperand(1);
12413 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012414 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012415 }
Owen Anderson9adc0ab2009-07-14 23:09:55 +000012416 return new ExtractElementInst(Src,
12417 Context->getConstantInt(Type::Int32Ty, SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012418 }
12419 }
Eli Friedman2451a642009-07-18 23:06:53 +000012420 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012421 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012422 return 0;
12423}
12424
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012425/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12426/// elements from either LHS or RHS, return the shuffle mask and true.
12427/// Otherwise, return false.
12428static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012429 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012430 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012431 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12432 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012433 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012434
12435 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012436 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012437 return true;
12438 } else if (V == LHS) {
12439 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012440 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012441 return true;
12442 } else if (V == RHS) {
12443 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012444 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012445 return true;
12446 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12447 // If this is an insert of an extract from some other vector, include it.
12448 Value *VecOp = IEI->getOperand(0);
12449 Value *ScalarOp = IEI->getOperand(1);
12450 Value *IdxOp = IEI->getOperand(2);
12451
Chris Lattnerd929f062006-04-27 21:14:21 +000012452 if (!isa<ConstantInt>(IdxOp))
12453 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012454 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012455
12456 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12457 // Okay, we can handle this if the vector we are insertinting into is
12458 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012459 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012460 // If so, update the mask to reflect the inserted undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012461 Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012462 return true;
12463 }
12464 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12465 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012466 EI->getOperand(0)->getType() == V->getType()) {
12467 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012468 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012469
12470 // This must be extracting from either LHS or RHS.
12471 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12472 // Okay, we can handle this if the vector we are insertinting into is
12473 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012474 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012475 // If so, update the mask to reflect the inserted value.
12476 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012477 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012478 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012479 } else {
12480 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012481 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012482 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012483
12484 }
12485 return true;
12486 }
12487 }
12488 }
12489 }
12490 }
12491 // TODO: Handle shufflevector here!
12492
12493 return false;
12494}
12495
12496/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12497/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12498/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012499static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012500 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012501 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012502 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012503 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012504 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012505
12506 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012507 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012508 return V;
12509 } else if (isa<ConstantAggregateZero>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012510 Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012511 return V;
12512 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12513 // If this is an insert of an extract from some other vector, include it.
12514 Value *VecOp = IEI->getOperand(0);
12515 Value *ScalarOp = IEI->getOperand(1);
12516 Value *IdxOp = IEI->getOperand(2);
12517
12518 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12519 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12520 EI->getOperand(0)->getType() == V->getType()) {
12521 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012522 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12523 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012524
12525 // Either the extracted from or inserted into vector must be RHSVec,
12526 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012527 if (EI->getOperand(0) == RHS || RHS == 0) {
12528 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012529 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012530 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012531 Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012532 return V;
12533 }
12534
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012535 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012536 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12537 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012538 // Everything but the extracted element is replaced with the RHS.
12539 for (unsigned i = 0; i != NumElts; ++i) {
12540 if (i != InsertedIdx)
Owen Andersond672ecb2009-07-03 00:17:18 +000012541 Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012542 }
12543 return V;
12544 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012545
12546 // If this insertelement is a chain that comes from exactly these two
12547 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012548 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12549 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012550 return EI->getOperand(0);
12551
Chris Lattnerefb47352006-04-15 01:39:45 +000012552 }
12553 }
12554 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012555 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012556
12557 // Otherwise, can't do anything fancy. Return an identity vector.
12558 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012559 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012560 return V;
12561}
12562
12563Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12564 Value *VecOp = IE.getOperand(0);
12565 Value *ScalarOp = IE.getOperand(1);
12566 Value *IdxOp = IE.getOperand(2);
12567
Chris Lattner599ded12007-04-09 01:11:16 +000012568 // Inserting an undef or into an undefined place, remove this.
12569 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12570 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012571
Chris Lattnerefb47352006-04-15 01:39:45 +000012572 // If the inserted element was extracted from some other vector, and if the
12573 // indexes are constant, try to turn this into a shufflevector operation.
12574 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12575 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12576 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012577 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012578 unsigned ExtractedIdx =
12579 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012580 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012581
12582 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12583 return ReplaceInstUsesWith(IE, VecOp);
12584
12585 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersond672ecb2009-07-03 00:17:18 +000012586 return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012587
12588 // If we are extracting a value from a vector, then inserting it right
12589 // back into the same place, just use the input vector.
12590 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12591 return ReplaceInstUsesWith(IE, VecOp);
12592
12593 // We could theoretically do this for ANY input. However, doing so could
12594 // turn chains of insertelement instructions into a chain of shufflevector
12595 // instructions, and right now we do not merge shufflevectors. As such,
12596 // only do this in a situation where it is clear that there is benefit.
12597 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12598 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12599 // the values of VecOp, except then one read from EIOp0.
12600 // Build a new shuffle mask.
12601 std::vector<Constant*> Mask;
12602 if (isa<UndefValue>(VecOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000012603 Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012604 else {
12605 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Andersond672ecb2009-07-03 00:17:18 +000012606 Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012607 NumVectorElts));
12608 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012609 Mask[InsertedIdx] =
12610 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012611 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersond672ecb2009-07-03 00:17:18 +000012612 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012613 }
12614
12615 // If this insertelement isn't used by some other insertelement, turn it
12616 // (and any insertelements it points to), into one big shuffle.
12617 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12618 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012619 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012620 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12621 if (RHS == 0) RHS = Context->getUndef(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012622 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012623 return new ShuffleVectorInst(LHS, RHS,
12624 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012625 }
12626 }
12627 }
12628
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012629 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12630 APInt UndefElts(VWidth, 0);
12631 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12632 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12633 return &IE;
12634
Chris Lattnerefb47352006-04-15 01:39:45 +000012635 return 0;
12636}
12637
12638
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012639Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12640 Value *LHS = SVI.getOperand(0);
12641 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012642 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012643
12644 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012645
Chris Lattner867b99f2006-10-05 06:55:50 +000012646 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012647 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012648 return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012649
Dan Gohman488fbfc2008-09-09 18:11:14 +000012650 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012651
12652 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12653 return 0;
12654
Evan Cheng388df622009-02-03 10:05:09 +000012655 APInt UndefElts(VWidth, 0);
12656 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12657 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012658 LHS = SVI.getOperand(0);
12659 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012660 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012661 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012662
Chris Lattner863bcff2006-05-25 23:48:38 +000012663 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12664 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12665 if (LHS == RHS || isa<UndefValue>(LHS)) {
12666 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012667 // shuffle(undef,undef,mask) -> undef.
12668 return ReplaceInstUsesWith(SVI, LHS);
12669 }
12670
Chris Lattner863bcff2006-05-25 23:48:38 +000012671 // Remap any references to RHS to use LHS.
12672 std::vector<Constant*> Elts;
12673 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012674 if (Mask[i] >= 2*e)
Owen Andersond672ecb2009-07-03 00:17:18 +000012675 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012676 else {
12677 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012678 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012679 Mask[i] = 2*e; // Turn into undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012680 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman4ce96272008-08-06 18:17:32 +000012681 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012682 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Andersond672ecb2009-07-03 00:17:18 +000012683 Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012684 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012685 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012686 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012687 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +000012688 SVI.setOperand(1, Context->getUndef(RHS->getType()));
12689 SVI.setOperand(2, Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012690 LHS = SVI.getOperand(0);
12691 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012692 MadeChange = true;
12693 }
12694
Chris Lattner7b2e27922006-05-26 00:29:06 +000012695 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012696 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012697
Chris Lattner863bcff2006-05-25 23:48:38 +000012698 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12699 if (Mask[i] >= e*2) continue; // Ignore undef values.
12700 // Is this an identity shuffle of the LHS value?
12701 isLHSID &= (Mask[i] == i);
12702
12703 // Is this an identity shuffle of the RHS value?
12704 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012705 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012706
Chris Lattner863bcff2006-05-25 23:48:38 +000012707 // Eliminate identity shuffles.
12708 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12709 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012710
Chris Lattner7b2e27922006-05-26 00:29:06 +000012711 // If the LHS is a shufflevector itself, see if we can combine it with this
12712 // one without producing an unusual shuffle. Here we are really conservative:
12713 // we are absolutely afraid of producing a shuffle mask not in the input
12714 // program, because the code gen may not be smart enough to turn a merged
12715 // shuffle into two specific shuffles: it may produce worse code. As such,
12716 // we only merge two shuffles if the result is one of the two input shuffle
12717 // masks. In this case, merging the shuffles just removes one instruction,
12718 // which we know is safe. This is good for things like turning:
12719 // (splat(splat)) -> splat.
12720 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12721 if (isa<UndefValue>(RHS)) {
12722 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12723
12724 std::vector<unsigned> NewMask;
12725 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12726 if (Mask[i] >= 2*e)
12727 NewMask.push_back(2*e);
12728 else
12729 NewMask.push_back(LHSMask[Mask[i]]);
12730
12731 // If the result mask is equal to the src shuffle or this shuffle mask, do
12732 // the replacement.
12733 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012734 unsigned LHSInNElts =
12735 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012736 std::vector<Constant*> Elts;
12737 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012738 if (NewMask[i] >= LHSInNElts*2) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012739 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012740 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012741 Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012742 }
12743 }
12744 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12745 LHSSVI->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +000012746 Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012747 }
12748 }
12749 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012750
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012751 return MadeChange ? &SVI : 0;
12752}
12753
12754
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012755
Chris Lattnerea1c4542004-12-08 23:43:58 +000012756
12757/// TryToSinkInstruction - Try to move the specified instruction from its
12758/// current block into the beginning of DestBlock, which can only happen if it's
12759/// safe to move the instruction past all of the instructions between it and the
12760/// end of its block.
12761static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12762 assert(I->hasOneUse() && "Invariants didn't hold!");
12763
Chris Lattner108e9022005-10-27 17:13:11 +000012764 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012765 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012766 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012767
Chris Lattnerea1c4542004-12-08 23:43:58 +000012768 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012769 if (isa<AllocaInst>(I) && I->getParent() ==
12770 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012771 return false;
12772
Chris Lattner96a52a62004-12-09 07:14:34 +000012773 // We can only sink load instructions if there is nothing between the load and
12774 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012775 if (I->mayReadFromMemory()) {
12776 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012777 Scan != E; ++Scan)
12778 if (Scan->mayWriteToMemory())
12779 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012780 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012781
Dan Gohman02dea8b2008-05-23 21:05:58 +000012782 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012783
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012784 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012785 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012786 ++NumSunkInst;
12787 return true;
12788}
12789
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012790
12791/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12792/// all reachable code to the worklist.
12793///
12794/// This has a couple of tricks to make the code faster and more powerful. In
12795/// particular, we constant fold and DCE instructions as we go, to avoid adding
12796/// them to the worklist (this significantly speeds up instcombine on code where
12797/// many instructions are dead or constant). Additionally, if we find a branch
12798/// whose condition is a known constant, we only visit the reachable successors.
12799///
12800static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012801 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012802 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012803 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012804 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012805 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012806
Chris Lattner2c7718a2007-03-23 19:17:18 +000012807 while (!Worklist.empty()) {
12808 BB = Worklist.back();
12809 Worklist.pop_back();
12810
12811 // We have now visited this block! If we've already been here, ignore it.
12812 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012813
12814 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012815 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12816 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012817
Chris Lattner2c7718a2007-03-23 19:17:18 +000012818 // DCE instruction if trivially dead.
12819 if (isInstructionTriviallyDead(Inst)) {
12820 ++NumDeadInst;
12821 DOUT << "IC: DCE: " << *Inst;
12822 Inst->eraseFromParent();
12823 continue;
12824 }
12825
12826 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012827 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000012828 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12829 Inst->replaceAllUsesWith(C);
12830 ++NumConstProp;
12831 Inst->eraseFromParent();
12832 continue;
12833 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012834
Devang Patel7fe1dec2008-11-19 18:56:50 +000012835 // If there are two consecutive llvm.dbg.stoppoint calls then
12836 // it is likely that the optimizer deleted code in between these
12837 // two intrinsics.
12838 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12839 if (DBI_Next) {
12840 if (DBI_Prev
12841 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12842 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12843 IC.RemoveFromWorkList(DBI_Prev);
12844 DBI_Prev->eraseFromParent();
12845 }
12846 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012847 } else {
12848 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012849 }
12850
Chris Lattner2c7718a2007-03-23 19:17:18 +000012851 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012852 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012853
12854 // Recursively visit successors. If this is a branch or switch on a
12855 // constant, only visit the reachable successor.
12856 TerminatorInst *TI = BB->getTerminator();
12857 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12858 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12859 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012860 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012861 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012862 continue;
12863 }
12864 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12865 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12866 // See if this is an explicit destination.
12867 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12868 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012869 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012870 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012871 continue;
12872 }
12873
12874 // Otherwise it is the default destination.
12875 Worklist.push_back(SI->getSuccessor(0));
12876 continue;
12877 }
12878 }
12879
12880 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12881 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012882 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012883}
12884
Chris Lattnerec9c3582007-03-03 02:04:50 +000012885bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012886 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000012887 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012888
12889 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12890 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012891
Chris Lattnerb3d59702005-07-07 20:40:38 +000012892 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012893 // Do a depth-first traversal of the function, populate the worklist with
12894 // the reachable instructions. Ignore blocks that are not reachable. Keep
12895 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012896 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012897 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012898
Chris Lattnerb3d59702005-07-07 20:40:38 +000012899 // Do a quick scan over the function. If we find any blocks that are
12900 // unreachable, remove any instructions inside of them. This prevents
12901 // the instcombine code from having to deal with some bad special cases.
12902 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12903 if (!Visited.count(BB)) {
12904 Instruction *Term = BB->getTerminator();
12905 while (Term != BB->begin()) { // Remove instrs bottom-up
12906 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012907
Bill Wendlingb7427032006-11-26 09:46:52 +000012908 DOUT << "IC: DCE: " << *I;
Dale Johannesenff278b12009-03-10 21:19:49 +000012909 // A debug intrinsic shouldn't force another iteration if we weren't
12910 // going to do one without it.
12911 if (!isa<DbgInfoIntrinsic>(I)) {
12912 ++NumDeadInst;
12913 Changed = true;
12914 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012915 if (!I->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000012916 I->replaceAllUsesWith(Context->getUndef(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012917 I->eraseFromParent();
12918 }
12919 }
12920 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012921
Chris Lattnerdbab3862007-03-02 21:28:56 +000012922 while (!Worklist.empty()) {
12923 Instruction *I = RemoveOneFromWorkList();
12924 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012925
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012926 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012927 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012928 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012929 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012930 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012931 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012932
Bill Wendlingb7427032006-11-26 09:46:52 +000012933 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012934
12935 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012936 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012937 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012938 continue;
12939 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012940
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012941 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012942 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012943 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012944
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012945 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012946 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000012947 ReplaceInstUsesWith(*I, C);
12948
Chris Lattner62b14df2002-09-02 04:59:56 +000012949 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012950 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012951 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012952 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012953 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012954 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012955
Eli Friedmanfd2934f2009-07-15 22:13:34 +000012956 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012957 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012958 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12959 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000012960 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12961 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012962 if (NewC != CE) {
12963 i->set(NewC);
12964 Changed = true;
12965 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012966 }
12967
Chris Lattnerea1c4542004-12-08 23:43:58 +000012968 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012969 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012970 BasicBlock *BB = I->getParent();
12971 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12972 if (UserParent != BB) {
12973 bool UserIsSuccessor = false;
12974 // See if the user is one of our successors.
12975 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12976 if (*SI == UserParent) {
12977 UserIsSuccessor = true;
12978 break;
12979 }
12980
12981 // If the user is one of our immediate successors, and if that successor
12982 // only has us as a predecessors (we'd have to split the critical edge
12983 // otherwise), we can keep going.
12984 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12985 next(pred_begin(UserParent)) == pred_end(UserParent))
12986 // Okay, the CFG is simple enough, try to sink this instruction.
12987 Changed |= TryToSinkInstruction(I, UserParent);
12988 }
12989 }
12990
Chris Lattner8a2a3112001-12-14 16:52:21 +000012991 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000012992#ifndef NDEBUG
12993 std::string OrigI;
12994#endif
12995 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000012996 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012997 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012998 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012999 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013000 DOUT << "IC: Old = " << *I
13001 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000013002
Chris Lattnerf523d062004-06-09 05:08:07 +000013003 // Everything uses the new instruction now.
13004 I->replaceAllUsesWith(Result);
13005
13006 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013007 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000013008 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013009
Chris Lattner6934a042007-02-11 01:23:03 +000013010 // Move the name to the new instruction first.
13011 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013012
13013 // Insert the new instruction into the basic block...
13014 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013015 BasicBlock::iterator InsertPos = I;
13016
13017 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13018 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13019 ++InsertPos;
13020
13021 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013022
Chris Lattner00d51312004-05-01 23:27:23 +000013023 // Make sure that we reprocess all operands now that we reduced their
13024 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013025 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000013026
Chris Lattnerf523d062004-06-09 05:08:07 +000013027 // Instructions can end up on the worklist more than once. Make sure
13028 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013029 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013030
13031 // Erase the old instruction.
13032 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000013033 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013034#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000013035 DOUT << "IC: Mod = " << OrigI
13036 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000013037#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013038
Chris Lattner90ac28c2002-08-02 19:29:35 +000013039 // If the instruction was modified, it's possible that it is now dead.
13040 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013041 if (isInstructionTriviallyDead(I)) {
13042 // Make sure we process all operands now that we are reducing their
13043 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000013044 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000013045
Chris Lattner00d51312004-05-01 23:27:23 +000013046 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013047 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013048 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000013049 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000013050 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000013051 AddToWorkList(I);
13052 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013053 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013054 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013055 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013056 }
13057 }
13058
Chris Lattnerec9c3582007-03-03 02:04:50 +000013059 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000013060
13061 // Do an explicit clear, this shrinks the map if needed.
13062 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013063 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013064}
13065
Chris Lattnerec9c3582007-03-03 02:04:50 +000013066
13067bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013068 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13069
Chris Lattnerec9c3582007-03-03 02:04:50 +000013070 bool EverMadeChange = false;
13071
13072 // Iterate while there is work to do.
13073 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013074 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013075 EverMadeChange = true;
13076 return EverMadeChange;
13077}
13078
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013079FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013080 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013081}