blob: dbdf449f60f2cd4b18cb62ad5f1cf442ab905ec2 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner173234a2008-06-02 01:18:21 +000045#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000046#include "llvm/Target/TargetData.h"
47#include "llvm/Transforms/Utils/BasicBlockUtils.h"
48#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000050#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000051#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000052#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000053#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000054#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000055#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000056#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000057#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000058#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000059#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000060#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000061#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000062#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000063#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000064#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000065#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000066using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000067using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000068
Chris Lattner0e5f4992006-12-19 21:40:18 +000069STATISTIC(NumCombined , "Number of insts combined");
70STATISTIC(NumConstProp, "Number of constant folds");
71STATISTIC(NumDeadInst , "Number of dead inst eliminated");
72STATISTIC(NumDeadStore, "Number of dead stores eliminated");
73STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000074
Chris Lattner0e5f4992006-12-19 21:40:18 +000075namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000076 class VISIBILITY_HIDDEN InstCombiner
77 : public FunctionPass,
78 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000079 // Worklist of all of the instructions that need to be simplified.
Chris Lattner2806dff2008-08-15 04:03:01 +000080 SmallVector<Instruction*, 256> Worklist;
Chris Lattnerdbab3862007-03-02 21:28:56 +000081 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000082 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000083 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000084 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000085 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000086 InstCombiner() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000087
Owen Anderson07cf79e2009-07-06 23:00:19 +000088 LLVMContext *getContext() { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +000089
Chris Lattnerdbab3862007-03-02 21:28:56 +000090 /// AddToWorkList - Add the specified instruction to the worklist if it
91 /// isn't already in it.
92 void AddToWorkList(Instruction *I) {
Dan Gohman6b345ee2008-07-07 17:46:23 +000093 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerdbab3862007-03-02 21:28:56 +000094 Worklist.push_back(I);
95 }
96
97 // RemoveFromWorkList - remove I from the worklist if it exists.
98 void RemoveFromWorkList(Instruction *I) {
99 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
100 if (It == WorklistMap.end()) return; // Not in worklist.
101
102 // Don't bother moving everything down, just null out the slot.
103 Worklist[It->second] = 0;
104
105 WorklistMap.erase(It);
106 }
107
108 Instruction *RemoveOneFromWorkList() {
109 Instruction *I = Worklist.back();
110 Worklist.pop_back();
111 WorklistMap.erase(I);
112 return I;
113 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000114
Chris Lattnerdbab3862007-03-02 21:28:56 +0000115
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000116 /// AddUsersToWorkList - When an instruction is simplified, add all users of
117 /// the instruction to the work lists because they might get more simplified
118 /// now.
119 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000120 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000121 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000122 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000123 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000124 }
125
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000126 /// AddUsesToWorkList - When an instruction is simplified, add operands to
127 /// the work lists because they might get more simplified now.
128 ///
129 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000130 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
131 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000132 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000133 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000134
135 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
136 /// dead. Add all of its operands to the worklist, turning them into
137 /// undef's to reduce the number of uses of those instructions.
138 ///
139 /// Return the specified operand before it is turned into an undef.
140 ///
141 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
142 Value *R = I.getOperand(op);
143
Gabor Greif177dd3f2008-06-12 21:37:33 +0000144 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
145 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000146 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000147 // Set the operand to undef to drop the use.
Owen Andersond672ecb2009-07-03 00:17:18 +0000148 *i = Context->getUndef(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000149 }
150
151 return R;
152 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000153
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000154 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000155 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000156
157 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000158
Chris Lattner97e52e42002-04-28 21:27:06 +0000159 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000160 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000161 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000162 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000163 }
164
Chris Lattner28977af2004-04-05 01:30:19 +0000165 TargetData &getTargetData() const { return *TD; }
166
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000167 // Visitation implementation - Implement instruction combining for different
168 // instruction types. The semantics are as follows:
169 // Return Value:
170 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000171 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000172 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000173 //
Chris Lattner7e708292002-06-25 16:13:24 +0000174 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000175 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000176 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000177 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000178 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000179 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000180 Instruction *visitURem(BinaryOperator &I);
181 Instruction *visitSRem(BinaryOperator &I);
182 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000183 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000184 Instruction *commonRemTransforms(BinaryOperator &I);
185 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000186 Instruction *commonDivTransforms(BinaryOperator &I);
187 Instruction *commonIDivTransforms(BinaryOperator &I);
188 Instruction *visitUDiv(BinaryOperator &I);
189 Instruction *visitSDiv(BinaryOperator &I);
190 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000191 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000192 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000193 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000194 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000195 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000196 Instruction *visitOr (BinaryOperator &I);
197 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000198 Instruction *visitShl(BinaryOperator &I);
199 Instruction *visitAShr(BinaryOperator &I);
200 Instruction *visitLShr(BinaryOperator &I);
201 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000202 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
203 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000204 Instruction *visitFCmpInst(FCmpInst &I);
205 Instruction *visitICmpInst(ICmpInst &I);
206 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000207 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
208 Instruction *LHS,
209 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000210 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
211 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000212
Reid Spencere4d87aa2006-12-23 06:05:41 +0000213 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
214 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000215 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000216 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000217 Instruction *commonCastTransforms(CastInst &CI);
218 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000219 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000220 Instruction *visitTrunc(TruncInst &CI);
221 Instruction *visitZExt(ZExtInst &CI);
222 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000223 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000224 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000225 Instruction *visitFPToUI(FPToUIInst &FI);
226 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000227 Instruction *visitUIToFP(CastInst &CI);
228 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000229 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000230 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000231 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000232 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
233 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000234 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000235 Instruction *visitSelectInst(SelectInst &SI);
236 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000237 Instruction *visitCallInst(CallInst &CI);
238 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000239 Instruction *visitPHINode(PHINode &PN);
240 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000241 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000242 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000243 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000244 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000245 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000246 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000247 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000248 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000249 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000250 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000251
252 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000253 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000254
Chris Lattner9fe38862003-06-19 17:00:31 +0000255 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000256 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000257 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000258 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000259 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
260 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000261 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000262 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
263
Chris Lattner9fe38862003-06-19 17:00:31 +0000264
Chris Lattner28977af2004-04-05 01:30:19 +0000265 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000266 // InsertNewInstBefore - insert an instruction New before instruction Old
267 // in the program. Add the new instruction to the worklist.
268 //
Chris Lattner955f3312004-09-28 21:48:02 +0000269 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000270 assert(New && New->getParent() == 0 &&
271 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000272 BasicBlock *BB = Old.getParent();
273 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000274 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000275 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000276 }
277
Chris Lattner0c967662004-09-24 15:21:34 +0000278 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
279 /// This also adds the cast to the worklist. Finally, this returns the
280 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000281 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
282 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000283 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000284
Chris Lattnere2ed0572006-04-06 19:19:17 +0000285 if (Constant *CV = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000286 return Context->getConstantExprCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000287
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000288 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000289 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000290 return C;
291 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000292
293 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
294 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
295 }
296
Chris Lattner0c967662004-09-24 15:21:34 +0000297
Chris Lattner8b170942002-08-09 23:47:40 +0000298 // ReplaceInstUsesWith - This method is to be used when an instruction is
299 // found to be dead, replacable with another preexisting expression. Here
300 // we add all uses of I to the worklist, replace all uses of I with the new
301 // value, then return I, so that the inst combiner will know that I was
302 // modified.
303 //
304 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000305 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000306 if (&I != V) {
307 I.replaceAllUsesWith(V);
308 return &I;
309 } else {
310 // If we are replacing the instruction with itself, this must be in a
311 // segment of unreachable code, so just clobber the instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +0000312 I.replaceAllUsesWith(Context->getUndef(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000313 return &I;
314 }
Chris Lattner8b170942002-08-09 23:47:40 +0000315 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000316
317 // EraseInstFromFunction - When dealing with an instruction that has side
318 // effects or produces a void value, we can't rely on DCE to delete the
319 // instruction. Instead, visit methods should return the value returned by
320 // this function.
321 Instruction *EraseInstFromFunction(Instruction &I) {
322 assert(I.use_empty() && "Cannot erase instruction that is used!");
323 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000324 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000325 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000326 return 0; // Don't do anything with FI
327 }
Chris Lattner173234a2008-06-02 01:18:21 +0000328
329 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
330 APInt &KnownOne, unsigned Depth = 0) const {
331 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
332 }
333
334 bool MaskedValueIsZero(Value *V, const APInt &Mask,
335 unsigned Depth = 0) const {
336 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
337 }
338 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
339 return llvm::ComputeNumSignBits(Op, TD, Depth);
340 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000341
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000342 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000343
Reid Spencere4d87aa2006-12-23 06:05:41 +0000344 /// SimplifyCommutative - This performs a few simplifications for
345 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000346 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000347
Reid Spencere4d87aa2006-12-23 06:05:41 +0000348 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
349 /// most-complex to least-complex order.
350 bool SimplifyCompare(CmpInst &I);
351
Chris Lattner886ab6c2009-01-31 08:15:18 +0000352 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
353 /// based on the demanded bits.
354 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
355 APInt& KnownZero, APInt& KnownOne,
356 unsigned Depth);
357 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000358 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000359 unsigned Depth=0);
360
361 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
362 /// SimplifyDemandedBits knows about. See if the instruction has any
363 /// properties that allow us to simplify its operands.
364 bool SimplifyDemandedInstructionBits(Instruction &Inst);
365
Evan Cheng388df622009-02-03 10:05:09 +0000366 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
367 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000368
Chris Lattner4e998b22004-09-29 05:07:12 +0000369 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
370 // PHI node as operand #0, see if we can fold the instruction into the PHI
371 // (which is only possible if all operands to the PHI are constants).
372 Instruction *FoldOpIntoPhi(Instruction &I);
373
Chris Lattnerbac32862004-11-14 19:13:23 +0000374 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
375 // operator and they all are only used by the PHI, PHI together their
376 // inputs, and do the operation once, to the result of the PHI.
377 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000378 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000379 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
380
Chris Lattner7da52b22006-11-01 04:51:18 +0000381
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000382 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
383 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000384
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000385 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000386 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000387 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000388 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000389 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000390 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000391 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000392 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000393 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000394
Chris Lattnerafe91a52006-06-15 19:07:26 +0000395
Reid Spencerc55b2432006-12-13 18:21:21 +0000396 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000397
Dan Gohman6de29f82009-06-15 22:12:54 +0000398 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000399 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000400 unsigned GetOrEnforceKnownAlignment(Value *V,
401 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000402
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000403 };
404}
405
Dan Gohman844731a2008-05-13 00:00:25 +0000406char InstCombiner::ID = 0;
407static RegisterPass<InstCombiner>
408X("instcombine", "Combine redundant instructions");
409
Chris Lattner4f98c562003-03-10 21:43:22 +0000410// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000411// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Owen Anderson0a5372e2009-07-13 04:09:18 +0000412static unsigned getComplexity(LLVMContext *Context, Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000413 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000414 if (BinaryOperator::isNeg(V) ||
415 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000416 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000417 return 3;
418 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000419 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000420 if (isa<Argument>(V)) return 3;
421 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000422}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000423
Chris Lattnerc8802d22003-03-11 00:12:48 +0000424// isOnlyUse - Return true if this instruction will be deleted if we stop using
425// it.
426static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000427 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000428}
429
Chris Lattner4cb170c2004-02-23 06:38:22 +0000430// getPromotedType - Return the specified type promoted as it would be to pass
431// though a va_arg area...
432static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000433 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
434 if (ITy->getBitWidth() < 32)
435 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000436 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000437 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000438}
439
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000440/// getBitCastOperand - If the specified operand is a CastInst, a constant
441/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
442/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000443static Value *getBitCastOperand(Value *V) {
444 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000445 // BitCastInst?
Chris Lattnereed48272005-09-13 00:40:14 +0000446 return I->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000447 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
448 // GetElementPtrInst?
449 if (GEP->hasAllZeroIndices())
450 return GEP->getOperand(0);
451 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000452 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000453 // BitCast ConstantExp?
Chris Lattnereed48272005-09-13 00:40:14 +0000454 return CE->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000455 else if (CE->getOpcode() == Instruction::GetElementPtr) {
456 // GetElementPtr ConstantExp?
457 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
458 I != E; ++I) {
459 ConstantInt *CI = dyn_cast<ConstantInt>(I);
460 if (!CI || !CI->isZero())
461 // Any non-zero indices? Not cast-like.
462 return 0;
463 }
464 // All-zero indices? This is just like casting.
465 return CE->getOperand(0);
466 }
467 }
Chris Lattnereed48272005-09-13 00:40:14 +0000468 return 0;
469}
470
Reid Spencer3da59db2006-11-27 01:05:10 +0000471/// This function is a wrapper around CastInst::isEliminableCastPair. It
472/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000473static Instruction::CastOps
474isEliminableCastPair(
475 const CastInst *CI, ///< The first cast instruction
476 unsigned opcode, ///< The opcode of the second cast instruction
477 const Type *DstTy, ///< The target type for the second cast instruction
478 TargetData *TD ///< The target data for pointer size
479) {
480
481 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
482 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000483
Reid Spencer3da59db2006-11-27 01:05:10 +0000484 // Get the opcodes of the two Cast instructions
485 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
486 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000487
Chris Lattnera0e69692009-03-24 18:35:40 +0000488 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
489 DstTy, TD->getIntPtrType());
490
491 // We don't want to form an inttoptr or ptrtoint that converts to an integer
492 // type that differs from the pointer size.
493 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
494 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
495 Res = 0;
496
497 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000498}
499
500/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
501/// in any code being generated. It does not require codegen if V is simple
502/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000503static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
504 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000505 if (V->getType() == Ty || isa<Constant>(V)) return false;
506
Chris Lattner01575b72006-05-25 23:24:33 +0000507 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000508 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000509 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000510 return false;
511 return true;
512}
513
Chris Lattner4f98c562003-03-10 21:43:22 +0000514// SimplifyCommutative - This performs a few simplifications for commutative
515// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000516//
Chris Lattner4f98c562003-03-10 21:43:22 +0000517// 1. Order operands such that they are listed from right (least complex) to
518// left (most complex). This puts constants before unary operators before
519// binary operators.
520//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000521// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
522// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000523//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000524bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000525 bool Changed = false;
Owen Anderson0a5372e2009-07-13 04:09:18 +0000526 if (getComplexity(Context, I.getOperand(0)) <
527 getComplexity(Context, I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000528 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000529
Chris Lattner4f98c562003-03-10 21:43:22 +0000530 if (!I.isAssociative()) return Changed;
531 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000532 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
533 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
534 if (isa<Constant>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000535 Constant *Folded = Context->getConstantExpr(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000536 cast<Constant>(I.getOperand(1)),
537 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000538 I.setOperand(0, Op->getOperand(0));
539 I.setOperand(1, Folded);
540 return true;
541 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
542 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
543 isOnlyUse(Op) && isOnlyUse(Op1)) {
544 Constant *C1 = cast<Constant>(Op->getOperand(1));
545 Constant *C2 = cast<Constant>(Op1->getOperand(1));
546
547 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersond672ecb2009-07-03 00:17:18 +0000548 Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000549 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000550 Op1->getOperand(0),
551 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000552 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000553 I.setOperand(0, New);
554 I.setOperand(1, Folded);
555 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000556 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000557 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000558 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000559}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000560
Reid Spencere4d87aa2006-12-23 06:05:41 +0000561/// SimplifyCompare - For a CmpInst this function just orders the operands
562/// so that theyare listed from right (least complex) to left (most complex).
563/// This puts constants before unary operators before binary operators.
564bool InstCombiner::SimplifyCompare(CmpInst &I) {
Owen Anderson0a5372e2009-07-13 04:09:18 +0000565 if (getComplexity(Context, I.getOperand(0)) >=
566 getComplexity(Context, I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000567 return false;
568 I.swapOperands();
569 // Compare instructions are not associative so there's nothing else we can do.
570 return true;
571}
572
Chris Lattner8d969642003-03-10 23:06:50 +0000573// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
574// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000575//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000576static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000577 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000578 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000579
Chris Lattner0ce85802004-12-14 20:08:06 +0000580 // Constants can be considered to be negated values if they can be folded.
581 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000582 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000583
584 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
585 if (C->getType()->getElementType()->isInteger())
Owen Andersond672ecb2009-07-03 00:17:18 +0000586 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000587
Chris Lattner8d969642003-03-10 23:06:50 +0000588 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000589}
590
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000591// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
592// instruction if the LHS is a constant negative zero (which is the 'negate'
593// form).
594//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000595static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000596 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000597 return BinaryOperator::getFNegArgument(V);
598
599 // Constants can be considered to be negated values if they can be folded.
600 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000601 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000602
603 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
604 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersond672ecb2009-07-03 00:17:18 +0000605 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000606
607 return 0;
608}
609
Owen Anderson07cf79e2009-07-06 23:00:19 +0000610static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
Chris Lattner8d969642003-03-10 23:06:50 +0000611 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000612 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000613
614 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000615 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000616 return Context->getConstantInt(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000617 return 0;
618}
619
Chris Lattnerc8802d22003-03-11 00:12:48 +0000620// dyn_castFoldableMul - If this value is a multiply that can be folded into
621// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000622// non-constant operand of the multiply, and set CST to point to the multiplier.
623// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000624//
Owen Andersond672ecb2009-07-03 00:17:18 +0000625static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000626 LLVMContext *Context) {
Chris Lattner42a75512007-01-15 02:27:26 +0000627 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000628 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000629 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000630 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000631 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000632 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000633 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000634 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000635 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000636 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Owen Andersond672ecb2009-07-03 00:17:18 +0000637 CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000638 return I->getOperand(0);
639 }
640 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000641 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000642}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000643
Chris Lattner574da9b2005-01-13 20:14:25 +0000644/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
645/// expression, return it.
646static User *dyn_castGetElementPtr(Value *V) {
647 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
648 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
649 if (CE->getOpcode() == Instruction::GetElementPtr)
650 return cast<User>(V);
651 return false;
652}
653
Reid Spencer7177c3a2007-03-25 05:33:51 +0000654/// AddOne - Add one to a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000655static Constant *AddOne(Constant *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000656 return Context->getConstantExprAdd(C,
657 Context->getConstantInt(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000658}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000659/// SubOne - Subtract one from a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000660static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000661 return Context->getConstantExprSub(C,
662 Context->getConstantInt(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000663}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000664/// MultiplyOverflows - True if the multiply can not be expressed in an int
665/// this size.
Owen Andersond672ecb2009-07-03 00:17:18 +0000666static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000667 LLVMContext *Context) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000668 uint32_t W = C1->getBitWidth();
669 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
670 if (sign) {
671 LHSExt.sext(W * 2);
672 RHSExt.sext(W * 2);
673 } else {
674 LHSExt.zext(W * 2);
675 RHSExt.zext(W * 2);
676 }
677
678 APInt MulExt = LHSExt * RHSExt;
679
680 if (sign) {
681 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
682 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
683 return MulExt.slt(Min) || MulExt.sgt(Max);
684 } else
685 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
686}
Chris Lattner955f3312004-09-28 21:48:02 +0000687
Reid Spencere7816b52007-03-08 01:52:58 +0000688
Chris Lattner255d8912006-02-11 09:31:47 +0000689/// ShrinkDemandedConstant - Check to see if the specified operand of the
690/// specified instruction is a constant integer. If so, check to see if there
691/// are any bits set in the constant that are not demanded. If so, shrink the
692/// constant and return true.
693static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000694 APInt Demanded, LLVMContext *Context) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000695 assert(I && "No instruction?");
696 assert(OpNo < I->getNumOperands() && "Operand index too large");
697
698 // If the operand is not a constant integer, nothing to do.
699 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
700 if (!OpC) return false;
701
702 // If there are no bits set that aren't demanded, nothing to do.
703 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
704 if ((~Demanded & OpC->getValue()) == 0)
705 return false;
706
707 // This instruction is producing bits that are not demanded. Shrink the RHS.
708 Demanded &= OpC->getValue();
Owen Andersond672ecb2009-07-03 00:17:18 +0000709 I->setOperand(OpNo, Context->getConstantInt(Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000710 return true;
711}
712
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000713// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
714// set of known zero and one bits, compute the maximum and minimum values that
715// could have the specified known zero and known one bits, returning them in
716// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000717static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000718 const APInt& KnownOne,
719 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000720 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
721 KnownZero.getBitWidth() == Min.getBitWidth() &&
722 KnownZero.getBitWidth() == Max.getBitWidth() &&
723 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000724 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000725
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000726 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
727 // bit if it is unknown.
728 Min = KnownOne;
729 Max = KnownOne|UnknownBits;
730
Dan Gohman1c8491e2009-04-25 17:12:48 +0000731 if (UnknownBits.isNegative()) { // Sign bit is unknown
732 Min.set(Min.getBitWidth()-1);
733 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000734 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000735}
736
737// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
738// a set of known zero and one bits, compute the maximum and minimum values that
739// could have the specified known zero and known one bits, returning them in
740// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000741static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000742 const APInt &KnownOne,
743 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000744 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
745 KnownZero.getBitWidth() == Min.getBitWidth() &&
746 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000747 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000748 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000749
750 // The minimum value is when the unknown bits are all zeros.
751 Min = KnownOne;
752 // The maximum value is when the unknown bits are all ones.
753 Max = KnownOne|UnknownBits;
754}
Chris Lattner255d8912006-02-11 09:31:47 +0000755
Chris Lattner886ab6c2009-01-31 08:15:18 +0000756/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
757/// SimplifyDemandedBits knows about. See if the instruction has any
758/// properties that allow us to simplify its operands.
759bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000760 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000761 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
762 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
763
764 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
765 KnownZero, KnownOne, 0);
766 if (V == 0) return false;
767 if (V == &Inst) return true;
768 ReplaceInstUsesWith(Inst, V);
769 return true;
770}
771
772/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
773/// specified instruction operand if possible, updating it in place. It returns
774/// true if it made any change and false otherwise.
775bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
776 APInt &KnownZero, APInt &KnownOne,
777 unsigned Depth) {
778 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
779 KnownZero, KnownOne, Depth);
780 if (NewVal == 0) return false;
781 U.set(NewVal);
782 return true;
783}
784
785
786/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
787/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000788/// that only the bits set in DemandedMask of the result of V are ever used
789/// downstream. Consequently, depending on the mask and V, it may be possible
790/// to replace V with a constant or one of its operands. In such cases, this
791/// function does the replacement and returns true. In all other cases, it
792/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000793/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000794/// to be zero in the expression. These are provided to potentially allow the
795/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
796/// the expression. KnownOne and KnownZero always follow the invariant that
797/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
798/// the bits in KnownOne and KnownZero may only be accurate for those bits set
799/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
800/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000801///
802/// This returns null if it did not change anything and it permits no
803/// simplification. This returns V itself if it did some simplification of V's
804/// operands based on the information about what bits are demanded. This returns
805/// some other non-null value if it found out that V is equal to another value
806/// in the context where the specified bits are demanded, but not for all users.
807Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
808 APInt &KnownZero, APInt &KnownOne,
809 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000810 assert(V != 0 && "Null pointer of Value???");
811 assert(Depth <= 6 && "Limit Search Depth");
812 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000813 const Type *VTy = V->getType();
814 assert((TD || !isa<PointerType>(VTy)) &&
815 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000816 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
817 (!VTy->isIntOrIntVector() ||
818 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000819 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000820 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000821 "Value *V, DemandedMask, KnownZero and KnownOne "
822 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000823 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
824 // We know all of the bits for a constant!
825 KnownOne = CI->getValue() & DemandedMask;
826 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000827 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000828 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000829 if (isa<ConstantPointerNull>(V)) {
830 // We know all of the bits for a constant!
831 KnownOne.clear();
832 KnownZero = DemandedMask;
833 return 0;
834 }
835
Chris Lattner08d2cc72009-01-31 07:26:06 +0000836 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000837 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000838 if (DemandedMask == 0) { // Not demanding any bits from V.
839 if (isa<UndefValue>(V))
840 return 0;
Owen Andersond672ecb2009-07-03 00:17:18 +0000841 return Context->getUndef(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000842 }
843
Chris Lattner4598c942009-01-31 08:24:16 +0000844 if (Depth == 6) // Limit search depth.
845 return 0;
846
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000847 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
848 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
849
Dan Gohman1c8491e2009-04-25 17:12:48 +0000850 Instruction *I = dyn_cast<Instruction>(V);
851 if (!I) {
852 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
853 return 0; // Only analyze instructions.
854 }
855
Chris Lattner4598c942009-01-31 08:24:16 +0000856 // If there are multiple uses of this value and we aren't at the root, then
857 // we can't do any simplifications of the operands, because DemandedMask
858 // only reflects the bits demanded by *one* of the users.
859 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000860 // Despite the fact that we can't simplify this instruction in all User's
861 // context, we can at least compute the knownzero/knownone bits, and we can
862 // do simplifications that apply to *just* the one user if we know that
863 // this instruction has a simpler value in that context.
864 if (I->getOpcode() == Instruction::And) {
865 // If either the LHS or the RHS are Zero, the result is zero.
866 ComputeMaskedBits(I->getOperand(1), DemandedMask,
867 RHSKnownZero, RHSKnownOne, Depth+1);
868 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
869 LHSKnownZero, LHSKnownOne, Depth+1);
870
871 // If all of the demanded bits are known 1 on one side, return the other.
872 // These bits cannot contribute to the result of the 'and' in this
873 // context.
874 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
875 (DemandedMask & ~LHSKnownZero))
876 return I->getOperand(0);
877 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
878 (DemandedMask & ~RHSKnownZero))
879 return I->getOperand(1);
880
881 // If all of the demanded bits in the inputs are known zeros, return zero.
882 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000883 return Context->getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000884
885 } else if (I->getOpcode() == Instruction::Or) {
886 // We can simplify (X|Y) -> X or Y in the user's context if we know that
887 // only bits from X or Y are demanded.
888
889 // If either the LHS or the RHS are One, the result is One.
890 ComputeMaskedBits(I->getOperand(1), DemandedMask,
891 RHSKnownZero, RHSKnownOne, Depth+1);
892 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
893 LHSKnownZero, LHSKnownOne, Depth+1);
894
895 // If all of the demanded bits are known zero on one side, return the
896 // other. These bits cannot contribute to the result of the 'or' in this
897 // context.
898 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
899 (DemandedMask & ~LHSKnownOne))
900 return I->getOperand(0);
901 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
902 (DemandedMask & ~RHSKnownOne))
903 return I->getOperand(1);
904
905 // If all of the potentially set bits on one side are known to be set on
906 // the other side, just use the 'other' side.
907 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
908 (DemandedMask & (~RHSKnownZero)))
909 return I->getOperand(0);
910 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
911 (DemandedMask & (~LHSKnownZero)))
912 return I->getOperand(1);
913 }
914
Chris Lattner4598c942009-01-31 08:24:16 +0000915 // Compute the KnownZero/KnownOne bits to simplify things downstream.
916 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
917 return 0;
918 }
919
920 // If this is the root being simplified, allow it to have multiple uses,
921 // just set the DemandedMask to all bits so that we can try to simplify the
922 // operands. This allows visitTruncInst (for example) to simplify the
923 // operand of a trunc without duplicating all the logic below.
924 if (Depth == 0 && !V->hasOneUse())
925 DemandedMask = APInt::getAllOnesValue(BitWidth);
926
Reid Spencer8cb68342007-03-12 17:25:59 +0000927 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000928 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000929 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000930 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000931 case Instruction::And:
932 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000933 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
934 RHSKnownZero, RHSKnownOne, Depth+1) ||
935 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000936 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000937 return I;
938 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
939 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000940
941 // If all of the demanded bits are known 1 on one side, return the other.
942 // These bits cannot contribute to the result of the 'and'.
943 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
944 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000945 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000946 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
947 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000948 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000949
950 // If all of the demanded bits in the inputs are known zeros, return zero.
951 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000952 return Context->getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000953
954 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000955 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000956 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000957
958 // Output known-1 bits are only known if set in both the LHS & RHS.
959 RHSKnownOne &= LHSKnownOne;
960 // Output known-0 are known to be clear if zero in either the LHS | RHS.
961 RHSKnownZero |= LHSKnownZero;
962 break;
963 case Instruction::Or:
964 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000965 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
966 RHSKnownZero, RHSKnownOne, Depth+1) ||
967 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000968 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000969 return I;
970 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
971 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000972
973 // If all of the demanded bits are known zero on one side, return the other.
974 // These bits cannot contribute to the result of the 'or'.
975 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
976 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000977 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000978 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
979 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000980 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000981
982 // If all of the potentially set bits on one side are known to be set on
983 // the other side, just use the 'other' side.
984 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
985 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000986 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000987 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
988 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000989 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000990
991 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000992 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000993 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000994
995 // Output known-0 bits are only known if clear in both the LHS & RHS.
996 RHSKnownZero &= LHSKnownZero;
997 // Output known-1 are known to be set if set in either the LHS | RHS.
998 RHSKnownOne |= LHSKnownOne;
999 break;
1000 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001001 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1002 RHSKnownZero, RHSKnownOne, Depth+1) ||
1003 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001004 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001005 return I;
1006 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1007 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001008
1009 // If all of the demanded bits are known zero on one side, return the other.
1010 // These bits cannot contribute to the result of the 'xor'.
1011 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001012 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001013 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001014 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001015
1016 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1017 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1018 (RHSKnownOne & LHSKnownOne);
1019 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1020 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1021 (RHSKnownOne & LHSKnownZero);
1022
1023 // If all of the demanded bits are known to be zero on one side or the
1024 // other, turn this into an *inclusive* or.
1025 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1026 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1027 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001028 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001029 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001030 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001031 }
1032
1033 // If all of the demanded bits on one side are known, and all of the set
1034 // bits on that side are also known to be set on the other side, turn this
1035 // into an AND, as we know the bits will be cleared.
1036 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1037 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1038 // all known
1039 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001040 Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001041 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001042 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001043 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001044 }
1045 }
1046
1047 // If the RHS is a constant, see if we can simplify it.
1048 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Owen Andersond672ecb2009-07-03 00:17:18 +00001049 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001050 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001051
1052 RHSKnownZero = KnownZeroOut;
1053 RHSKnownOne = KnownOneOut;
1054 break;
1055 }
1056 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001057 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1058 RHSKnownZero, RHSKnownOne, Depth+1) ||
1059 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001060 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001061 return I;
1062 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1063 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001064
1065 // If the operands are constants, see if we can simplify them.
Owen Andersond672ecb2009-07-03 00:17:18 +00001066 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1067 ShrinkDemandedConstant(I, 2, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001068 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001069
1070 // Only known if known in both the LHS and RHS.
1071 RHSKnownOne &= LHSKnownOne;
1072 RHSKnownZero &= LHSKnownZero;
1073 break;
1074 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001075 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001076 DemandedMask.zext(truncBf);
1077 RHSKnownZero.zext(truncBf);
1078 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001079 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001080 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001081 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001082 DemandedMask.trunc(BitWidth);
1083 RHSKnownZero.trunc(BitWidth);
1084 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001085 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001086 break;
1087 }
1088 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001089 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001090 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001091
1092 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1093 if (const VectorType *SrcVTy =
1094 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1095 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1096 // Don't touch a bitcast between vectors of different element counts.
1097 return false;
1098 } else
1099 // Don't touch a scalar-to-vector bitcast.
1100 return false;
1101 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1102 // Don't touch a vector-to-scalar bitcast.
1103 return false;
1104
Chris Lattner886ab6c2009-01-31 08:15:18 +00001105 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001106 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001107 return I;
1108 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001109 break;
1110 case Instruction::ZExt: {
1111 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001112 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001113
Zhou Shengd48653a2007-03-29 04:45:55 +00001114 DemandedMask.trunc(SrcBitWidth);
1115 RHSKnownZero.trunc(SrcBitWidth);
1116 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001117 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001118 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001119 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001120 DemandedMask.zext(BitWidth);
1121 RHSKnownZero.zext(BitWidth);
1122 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001123 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001124 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001125 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001126 break;
1127 }
1128 case Instruction::SExt: {
1129 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001130 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001131
Reid Spencer8cb68342007-03-12 17:25:59 +00001132 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001133 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001134
Zhou Sheng01542f32007-03-29 02:26:30 +00001135 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001136 // If any of the sign extended bits are demanded, we know that the sign
1137 // bit is demanded.
1138 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001139 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001140
Zhou Shengd48653a2007-03-29 04:45:55 +00001141 InputDemandedBits.trunc(SrcBitWidth);
1142 RHSKnownZero.trunc(SrcBitWidth);
1143 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001144 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001145 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001146 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001147 InputDemandedBits.zext(BitWidth);
1148 RHSKnownZero.zext(BitWidth);
1149 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001150 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001151
1152 // If the sign bit of the input is known set or clear, then we know the
1153 // top bits of the result.
1154
1155 // If the input sign bit is known zero, or if the NewBits are not demanded
1156 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001157 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001158 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001159 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1160 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001161 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001162 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001163 }
1164 break;
1165 }
1166 case Instruction::Add: {
1167 // Figure out what the input bits are. If the top bits of the and result
1168 // are not demanded, then the add doesn't demand them from its input
1169 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001170 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001171
1172 // If there is a constant on the RHS, there are a variety of xformations
1173 // we can do.
1174 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1175 // If null, this should be simplified elsewhere. Some of the xforms here
1176 // won't work if the RHS is zero.
1177 if (RHS->isZero())
1178 break;
1179
1180 // If the top bit of the output is demanded, demand everything from the
1181 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001182 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001183
1184 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001185 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001186 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001187 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001188
1189 // If the RHS of the add has bits set that can't affect the input, reduce
1190 // the constant.
Owen Andersond672ecb2009-07-03 00:17:18 +00001191 if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001192 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001193
1194 // Avoid excess work.
1195 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1196 break;
1197
1198 // Turn it into OR if input bits are zero.
1199 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1200 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001201 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001202 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001203 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001204 }
1205
1206 // We can say something about the output known-zero and known-one bits,
1207 // depending on potential carries from the input constant and the
1208 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1209 // bits set and the RHS constant is 0x01001, then we know we have a known
1210 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1211
1212 // To compute this, we first compute the potential carry bits. These are
1213 // the bits which may be modified. I'm not aware of a better way to do
1214 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001215 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001216 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001217
1218 // Now that we know which bits have carries, compute the known-1/0 sets.
1219
1220 // Bits are known one if they are known zero in one operand and one in the
1221 // other, and there is no input carry.
1222 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1223 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1224
1225 // Bits are known zero if they are known zero in both operands and there
1226 // is no input carry.
1227 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1228 } else {
1229 // If the high-bits of this ADD are not demanded, then it does not demand
1230 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001231 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001232 // Right fill the mask of bits for this ADD to demand the most
1233 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001234 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001235 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1236 LHSKnownZero, LHSKnownOne, Depth+1) ||
1237 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001238 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001239 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001240 }
1241 }
1242 break;
1243 }
1244 case Instruction::Sub:
1245 // If the high-bits of this SUB are not demanded, then it does not demand
1246 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001247 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001248 // Right fill the mask of bits for this SUB to demand the most
1249 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001250 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001251 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001252 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1253 LHSKnownZero, LHSKnownOne, Depth+1) ||
1254 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001255 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001256 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001257 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001258 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1259 // the known zeros and ones.
1260 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001261 break;
1262 case Instruction::Shl:
1263 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001264 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001265 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001266 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001267 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001268 return I;
1269 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001270 RHSKnownZero <<= ShiftAmt;
1271 RHSKnownOne <<= ShiftAmt;
1272 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001273 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001274 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001275 }
1276 break;
1277 case Instruction::LShr:
1278 // For a logical shift right
1279 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001280 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001281
Reid Spencer8cb68342007-03-12 17:25:59 +00001282 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001283 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001284 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001285 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001286 return I;
1287 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001288 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1289 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001290 if (ShiftAmt) {
1291 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001292 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001293 RHSKnownZero |= HighBits; // high bits known zero.
1294 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001295 }
1296 break;
1297 case Instruction::AShr:
1298 // If this is an arithmetic shift right and only the low-bit is set, we can
1299 // always convert this into a logical shr, even if the shift amount is
1300 // variable. The low bit of the shift cannot be an input sign bit unless
1301 // the shift amount is >= the size of the datatype, which is undefined.
1302 if (DemandedMask == 1) {
1303 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001304 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001305 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001306 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001307 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001308
1309 // If the sign bit is the only bit demanded by this ashr, then there is no
1310 // need to do it, the shift doesn't change the high bit.
1311 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001312 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001313
1314 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001315 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001316
Reid Spencer8cb68342007-03-12 17:25:59 +00001317 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001318 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001319 // If any of the "high bits" are demanded, we should set the sign bit as
1320 // demanded.
1321 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1322 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001323 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001324 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001325 return I;
1326 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001327 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001328 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001329 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1330 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1331
1332 // Handle the sign bits.
1333 APInt SignBit(APInt::getSignBit(BitWidth));
1334 // Adjust to where it is now in the mask.
1335 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1336
1337 // If the input sign bit is known to be zero, or if none of the top bits
1338 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001339 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001340 (HighBits & ~DemandedMask) == HighBits) {
1341 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001342 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001343 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001344 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001345 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1346 RHSKnownOne |= HighBits;
1347 }
1348 }
1349 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001350 case Instruction::SRem:
1351 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001352 APInt RA = Rem->getValue().abs();
1353 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001354 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001355 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001356
Nick Lewycky8e394322008-11-02 02:41:50 +00001357 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001358 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001359 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001360 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001361 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001362
1363 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1364 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001365
1366 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001367
Chris Lattner886ab6c2009-01-31 08:15:18 +00001368 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001369 }
1370 }
1371 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001372 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001373 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1374 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001375 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1376 KnownZero2, KnownOne2, Depth+1) ||
1377 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001378 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001379 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001380
Chris Lattner455e9ab2009-01-21 18:09:24 +00001381 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001382 Leaders = std::max(Leaders,
1383 KnownZero2.countLeadingOnes());
1384 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001385 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001386 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001387 case Instruction::Call:
1388 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1389 switch (II->getIntrinsicID()) {
1390 default: break;
1391 case Intrinsic::bswap: {
1392 // If the only bits demanded come from one byte of the bswap result,
1393 // just shift the input byte into position to eliminate the bswap.
1394 unsigned NLZ = DemandedMask.countLeadingZeros();
1395 unsigned NTZ = DemandedMask.countTrailingZeros();
1396
1397 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1398 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1399 // have 14 leading zeros, round to 8.
1400 NLZ &= ~7;
1401 NTZ &= ~7;
1402 // If we need exactly one byte, we can do this transformation.
1403 if (BitWidth-NLZ-NTZ == 8) {
1404 unsigned ResultBit = NTZ;
1405 unsigned InputBit = BitWidth-NTZ-8;
1406
1407 // Replace this with either a left or right shift to get the byte into
1408 // the right place.
1409 Instruction *NewVal;
1410 if (InputBit > ResultBit)
1411 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00001412 Context->getConstantInt(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001413 else
1414 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00001415 Context->getConstantInt(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001416 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001417 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001418 }
1419
1420 // TODO: Could compute known zero/one bits based on the input.
1421 break;
1422 }
1423 }
1424 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001425 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001426 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001427 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001428
1429 // If the client is only demanding bits that we know, return the known
1430 // constant.
Dan Gohman1c8491e2009-04-25 17:12:48 +00001431 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001432 Constant *C = Context->getConstantInt(RHSKnownOne);
Dan Gohman1c8491e2009-04-25 17:12:48 +00001433 if (isa<PointerType>(V->getType()))
Owen Andersond672ecb2009-07-03 00:17:18 +00001434 C = Context->getConstantExprIntToPtr(C, V->getType());
Dan Gohman1c8491e2009-04-25 17:12:48 +00001435 return C;
1436 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001437 return false;
1438}
1439
Chris Lattner867b99f2006-10-05 06:55:50 +00001440
Mon P Wangaeb06d22008-11-10 04:46:22 +00001441/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001442/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001443/// actually used by the caller. This method analyzes which elements of the
1444/// operand are undef and returns that information in UndefElts.
1445///
1446/// If the information about demanded elements can be used to simplify the
1447/// operation, the operation is simplified, then the resultant value is
1448/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001449Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1450 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001451 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001452 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001453 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001454 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001455
1456 if (isa<UndefValue>(V)) {
1457 // If the entire vector is undefined, just return this info.
1458 UndefElts = EltMask;
1459 return 0;
1460 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1461 UndefElts = EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001462 return Context->getUndef(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001463 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001464
Chris Lattner867b99f2006-10-05 06:55:50 +00001465 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001466 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1467 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001468 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001469
1470 std::vector<Constant*> Elts;
1471 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001472 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001473 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001474 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001475 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1476 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001477 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001478 } else { // Otherwise, defined.
1479 Elts.push_back(CP->getOperand(i));
1480 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001481
Chris Lattner867b99f2006-10-05 06:55:50 +00001482 // If we changed the constant, return it.
Owen Andersond672ecb2009-07-03 00:17:18 +00001483 Constant *NewCP = Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001484 return NewCP != CP ? NewCP : 0;
1485 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001486 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001487 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001488
1489 // Check if this is identity. If so, return 0 since we are not simplifying
1490 // anything.
1491 if (DemandedElts == ((1ULL << VWidth) -1))
1492 return 0;
1493
Reid Spencer9d6565a2007-02-15 02:26:10 +00001494 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001495 Constant *Zero = Context->getNullValue(EltTy);
1496 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001497 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001498 for (unsigned i = 0; i != VWidth; ++i) {
1499 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1500 Elts.push_back(Elt);
1501 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001502 UndefElts = DemandedElts ^ EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001503 return Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001504 }
1505
Dan Gohman488fbfc2008-09-09 18:11:14 +00001506 // Limit search depth.
1507 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001508 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001509
1510 // If multiple users are using the root value, procede with
1511 // simplification conservatively assuming that all elements
1512 // are needed.
1513 if (!V->hasOneUse()) {
1514 // Quit if we find multiple users of a non-root value though.
1515 // They'll be handled when it's their turn to be visited by
1516 // the main instcombine process.
1517 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001518 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001519 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001520
1521 // Conservatively assume that all elements are needed.
1522 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001523 }
1524
1525 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001526 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001527
1528 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001529 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001530 Value *TmpV;
1531 switch (I->getOpcode()) {
1532 default: break;
1533
1534 case Instruction::InsertElement: {
1535 // If this is a variable index, we don't know which element it overwrites.
1536 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001537 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001538 if (Idx == 0) {
1539 // Note that we can't propagate undef elt info, because we don't know
1540 // which elt is getting updated.
1541 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1542 UndefElts2, Depth+1);
1543 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1544 break;
1545 }
1546
1547 // If this is inserting an element that isn't demanded, remove this
1548 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001549 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001550 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001551 return AddSoonDeadInstToWorklist(*I, 0);
1552
1553 // Otherwise, the element inserted overwrites whatever was there, so the
1554 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001555 APInt DemandedElts2 = DemandedElts;
1556 DemandedElts2.clear(IdxNo);
1557 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001558 UndefElts, Depth+1);
1559 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1560
1561 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001562 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001563 break;
1564 }
1565 case Instruction::ShuffleVector: {
1566 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001567 uint64_t LHSVWidth =
1568 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001569 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001570 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001571 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001572 unsigned MaskVal = Shuffle->getMaskValue(i);
1573 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001574 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001575 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001576 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001577 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001578 else
Evan Cheng388df622009-02-03 10:05:09 +00001579 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001580 }
1581 }
1582 }
1583
Nate Begeman7b254672009-02-11 22:36:25 +00001584 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001585 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001586 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001587 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1588
Nate Begeman7b254672009-02-11 22:36:25 +00001589 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001590 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1591 UndefElts3, Depth+1);
1592 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1593
1594 bool NewUndefElts = false;
1595 for (unsigned i = 0; i < VWidth; i++) {
1596 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001597 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001598 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001599 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001600 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001601 NewUndefElts = true;
1602 UndefElts.set(i);
1603 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001604 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001605 if (UndefElts3[MaskVal - LHSVWidth]) {
1606 NewUndefElts = true;
1607 UndefElts.set(i);
1608 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001609 }
1610 }
1611
1612 if (NewUndefElts) {
1613 // Add additional discovered undefs.
1614 std::vector<Constant*> Elts;
1615 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001616 if (UndefElts[i])
Owen Andersond672ecb2009-07-03 00:17:18 +00001617 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001618 else
Owen Andersond672ecb2009-07-03 00:17:18 +00001619 Elts.push_back(Context->getConstantInt(Type::Int32Ty,
Dan Gohman488fbfc2008-09-09 18:11:14 +00001620 Shuffle->getMaskValue(i)));
1621 }
Owen Andersond672ecb2009-07-03 00:17:18 +00001622 I->setOperand(2, Context->getConstantVector(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001623 MadeChange = true;
1624 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001625 break;
1626 }
Chris Lattner69878332007-04-14 22:29:23 +00001627 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001628 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001629 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1630 if (!VTy) break;
1631 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001632 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001633 unsigned Ratio;
1634
1635 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001636 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001637 // elements as are demanded of us.
1638 Ratio = 1;
1639 InputDemandedElts = DemandedElts;
1640 } else if (VWidth > InVWidth) {
1641 // Untested so far.
1642 break;
1643
1644 // If there are more elements in the result than there are in the source,
1645 // then an input element is live if any of the corresponding output
1646 // elements are live.
1647 Ratio = VWidth/InVWidth;
1648 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001649 if (DemandedElts[OutIdx])
1650 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001651 }
1652 } else {
1653 // Untested so far.
1654 break;
1655
1656 // If there are more elements in the source than there are in the result,
1657 // then an input element is live if the corresponding output element is
1658 // live.
1659 Ratio = InVWidth/VWidth;
1660 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001661 if (DemandedElts[InIdx/Ratio])
1662 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001663 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001664
Chris Lattner69878332007-04-14 22:29:23 +00001665 // div/rem demand all inputs, because they don't want divide by zero.
1666 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1667 UndefElts2, Depth+1);
1668 if (TmpV) {
1669 I->setOperand(0, TmpV);
1670 MadeChange = true;
1671 }
1672
1673 UndefElts = UndefElts2;
1674 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001675 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001676 // If there are more elements in the result than there are in the source,
1677 // then an output element is undef if the corresponding input element is
1678 // undef.
1679 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001680 if (UndefElts2[OutIdx/Ratio])
1681 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001682 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001683 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001684 // If there are more elements in the source than there are in the result,
1685 // then a result element is undef if all of the corresponding input
1686 // elements are undef.
1687 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1688 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001689 if (!UndefElts2[InIdx]) // Not undef?
1690 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001691 }
1692 break;
1693 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001694 case Instruction::And:
1695 case Instruction::Or:
1696 case Instruction::Xor:
1697 case Instruction::Add:
1698 case Instruction::Sub:
1699 case Instruction::Mul:
1700 // div/rem demand all inputs, because they don't want divide by zero.
1701 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1702 UndefElts, Depth+1);
1703 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1704 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1705 UndefElts2, Depth+1);
1706 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1707
1708 // Output elements are undefined if both are undefined. Consider things
1709 // like undef&0. The result is known zero, not undef.
1710 UndefElts &= UndefElts2;
1711 break;
1712
1713 case Instruction::Call: {
1714 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1715 if (!II) break;
1716 switch (II->getIntrinsicID()) {
1717 default: break;
1718
1719 // Binary vector operations that work column-wise. A dest element is a
1720 // function of the corresponding input elements from the two inputs.
1721 case Intrinsic::x86_sse_sub_ss:
1722 case Intrinsic::x86_sse_mul_ss:
1723 case Intrinsic::x86_sse_min_ss:
1724 case Intrinsic::x86_sse_max_ss:
1725 case Intrinsic::x86_sse2_sub_sd:
1726 case Intrinsic::x86_sse2_mul_sd:
1727 case Intrinsic::x86_sse2_min_sd:
1728 case Intrinsic::x86_sse2_max_sd:
1729 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1730 UndefElts, Depth+1);
1731 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1732 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1733 UndefElts2, Depth+1);
1734 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1735
1736 // If only the low elt is demanded and this is a scalarizable intrinsic,
1737 // scalarize it now.
1738 if (DemandedElts == 1) {
1739 switch (II->getIntrinsicID()) {
1740 default: break;
1741 case Intrinsic::x86_sse_sub_ss:
1742 case Intrinsic::x86_sse_mul_ss:
1743 case Intrinsic::x86_sse2_sub_sd:
1744 case Intrinsic::x86_sse2_mul_sd:
1745 // TODO: Lower MIN/MAX/ABS/etc
1746 Value *LHS = II->getOperand(1);
1747 Value *RHS = II->getOperand(2);
1748 // Extract the element as scalars.
Owen Anderson9adc0ab2009-07-14 23:09:55 +00001749 LHS = InsertNewInstBefore(new ExtractElementInst(LHS,
1750 Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1751 RHS = InsertNewInstBefore(new ExtractElementInst(RHS,
1752 Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001753
1754 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001755 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001756 case Intrinsic::x86_sse_sub_ss:
1757 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001758 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001759 II->getName()), *II);
1760 break;
1761 case Intrinsic::x86_sse_mul_ss:
1762 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001763 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001764 II->getName()), *II);
1765 break;
1766 }
1767
1768 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001769 InsertElementInst::Create(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00001770 Context->getUndef(II->getType()), TmpV,
1771 Context->getConstantInt(Type::Int32Ty, 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001772 InsertNewInstBefore(New, *II);
1773 AddSoonDeadInstToWorklist(*II, 0);
1774 return New;
1775 }
1776 }
1777
1778 // Output elements are undefined if both are undefined. Consider things
1779 // like undef&0. The result is known zero, not undef.
1780 UndefElts &= UndefElts2;
1781 break;
1782 }
1783 break;
1784 }
1785 }
1786 return MadeChange ? I : 0;
1787}
1788
Dan Gohman45b4e482008-05-19 22:14:15 +00001789
Chris Lattner564a7272003-08-13 19:01:45 +00001790/// AssociativeOpt - Perform an optimization on an associative operator. This
1791/// function is designed to check a chain of associative operators for a
1792/// potential to apply a certain optimization. Since the optimization may be
1793/// applicable if the expression was reassociated, this checks the chain, then
1794/// reassociates the expression as necessary to expose the optimization
1795/// opportunity. This makes use of a special Functor, which must define
1796/// 'shouldApply' and 'apply' methods.
1797///
1798template<typename Functor>
Owen Andersond672ecb2009-07-03 00:17:18 +00001799static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001800 LLVMContext *Context) {
Chris Lattner564a7272003-08-13 19:01:45 +00001801 unsigned Opcode = Root.getOpcode();
1802 Value *LHS = Root.getOperand(0);
1803
1804 // Quick check, see if the immediate LHS matches...
1805 if (F.shouldApply(LHS))
1806 return F.apply(Root);
1807
1808 // Otherwise, if the LHS is not of the same opcode as the root, return.
1809 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001810 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001811 // Should we apply this transform to the RHS?
1812 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1813
1814 // If not to the RHS, check to see if we should apply to the LHS...
1815 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1816 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1817 ShouldApply = true;
1818 }
1819
1820 // If the functor wants to apply the optimization to the RHS of LHSI,
1821 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1822 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001823 // Now all of the instructions are in the current basic block, go ahead
1824 // and perform the reassociation.
1825 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1826
1827 // First move the selected RHS to the LHS of the root...
1828 Root.setOperand(0, LHSI->getOperand(1));
1829
1830 // Make what used to be the LHS of the root be the user of the root...
1831 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001832 if (&Root == TmpLHSI) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001833 Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001834 return 0;
1835 }
Chris Lattner65725312004-04-16 18:08:07 +00001836 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001837 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001838 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001839 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001840 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001841
1842 // Now propagate the ExtraOperand down the chain of instructions until we
1843 // get to LHSI.
1844 while (TmpLHSI != LHSI) {
1845 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001846 // Move the instruction to immediately before the chain we are
1847 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001848 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001849 ARI = NextLHSI;
1850
Chris Lattner564a7272003-08-13 19:01:45 +00001851 Value *NextOp = NextLHSI->getOperand(1);
1852 NextLHSI->setOperand(1, ExtraOperand);
1853 TmpLHSI = NextLHSI;
1854 ExtraOperand = NextOp;
1855 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001856
Chris Lattner564a7272003-08-13 19:01:45 +00001857 // Now that the instructions are reassociated, have the functor perform
1858 // the transformation...
1859 return F.apply(Root);
1860 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001861
Chris Lattner564a7272003-08-13 19:01:45 +00001862 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1863 }
1864 return 0;
1865}
1866
Dan Gohman844731a2008-05-13 00:00:25 +00001867namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001868
Nick Lewycky02d639f2008-05-23 04:34:58 +00001869// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001870struct AddRHS {
1871 Value *RHS;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001872 LLVMContext *Context;
1873 AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001874 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1875 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001876 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00001877 Context->getConstantInt(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001878 }
1879};
1880
1881// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1882// iff C1&C2 == 0
1883struct AddMaskingAnd {
1884 Constant *C2;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001885 LLVMContext *Context;
1886 AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001887 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001888 ConstantInt *C1;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00001889 return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
Owen Andersond672ecb2009-07-03 00:17:18 +00001890 Context->getConstantExprAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001891 }
1892 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001893 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001894 }
1895};
1896
Dan Gohman844731a2008-05-13 00:00:25 +00001897}
1898
Chris Lattner6e7ba452005-01-01 16:22:27 +00001899static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001900 InstCombiner *IC) {
Owen Anderson07cf79e2009-07-06 23:00:19 +00001901 LLVMContext *Context = IC->getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00001902
Reid Spencer3da59db2006-11-27 01:05:10 +00001903 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001904 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001905 }
1906
Chris Lattner2eefe512004-04-09 19:05:30 +00001907 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001908 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1909 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001910
Chris Lattner2eefe512004-04-09 19:05:30 +00001911 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1912 if (ConstIsRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00001913 return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1914 return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001915 }
1916
1917 Value *Op0 = SO, *Op1 = ConstOperand;
1918 if (!ConstIsRHS)
1919 std::swap(Op0, Op1);
1920 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001921 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001922 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001923 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00001924 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1925 Op0, Op1, SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001926 else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001927 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001928 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001929 return IC->InsertNewInstBefore(New, I);
1930}
1931
1932// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1933// constant as the other operand, try to fold the binary operator into the
1934// select arguments. This also works for Cast instructions, which obviously do
1935// not have a second operand.
1936static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1937 InstCombiner *IC) {
1938 // Don't modify shared select instructions
1939 if (!SI->hasOneUse()) return 0;
1940 Value *TV = SI->getOperand(1);
1941 Value *FV = SI->getOperand(2);
1942
1943 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001944 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001945 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001946
Chris Lattner6e7ba452005-01-01 16:22:27 +00001947 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1948 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1949
Gabor Greif051a9502008-04-06 20:25:17 +00001950 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1951 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001952 }
1953 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001954}
1955
Chris Lattner4e998b22004-09-29 05:07:12 +00001956
1957/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1958/// node as operand #0, see if we can fold the instruction into the PHI (which
1959/// is only possible if all operands to the PHI are constants).
1960Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1961 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001962 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001963 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001964
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001965 // Check to see if all of the operands of the PHI are constants. If there is
1966 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001967 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001968 BasicBlock *NonConstBB = 0;
1969 for (unsigned i = 0; i != NumPHIValues; ++i)
1970 if (!isa<Constant>(PN->getIncomingValue(i))) {
1971 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001972 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001973 NonConstBB = PN->getIncomingBlock(i);
1974
1975 // If the incoming non-constant value is in I's block, we have an infinite
1976 // loop.
1977 if (NonConstBB == I.getParent())
1978 return 0;
1979 }
1980
1981 // If there is exactly one non-constant value, we can insert a copy of the
1982 // operation in that block. However, if this is a critical edge, we would be
1983 // inserting the computation one some other paths (e.g. inside a loop). Only
1984 // do this if the pred block is unconditionally branching into the phi block.
1985 if (NonConstBB) {
1986 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1987 if (!BI || !BI->isUnconditional()) return 0;
1988 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001989
1990 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001991 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001992 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001993 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001994 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001995
1996 // Next, add all of the operands to the PHI.
1997 if (I.getNumOperands() == 2) {
1998 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001999 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002000 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002001 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002002 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersond672ecb2009-07-03 00:17:18 +00002003 InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002004 else
Owen Andersond672ecb2009-07-03 00:17:18 +00002005 InV = Context->getConstantExpr(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002006 } else {
2007 assert(PN->getIncomingBlock(i) == NonConstBB);
2008 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002009 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002010 PN->getIncomingValue(i), C, "phitmp",
2011 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002012 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00002013 InV = CmpInst::Create(*Context, CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002014 CI->getPredicate(),
2015 PN->getIncomingValue(i), C, "phitmp",
2016 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002017 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002018 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002019
Chris Lattnerdbab3862007-03-02 21:28:56 +00002020 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002021 }
2022 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002023 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002024 } else {
2025 CastInst *CI = cast<CastInst>(&I);
2026 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002027 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002028 Value *InV;
2029 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002030 InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002031 } else {
2032 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002033 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002034 I.getType(), "phitmp",
2035 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002036 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002037 }
2038 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002039 }
2040 }
2041 return ReplaceInstUsesWith(I, NewPN);
2042}
2043
Chris Lattner2454a2e2008-01-29 06:52:45 +00002044
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002045/// WillNotOverflowSignedAdd - Return true if we can prove that:
2046/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2047/// This basically requires proving that the add in the original type would not
2048/// overflow to change the sign bit or have a carry out.
2049bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2050 // There are different heuristics we can use for this. Here are some simple
2051 // ones.
2052
2053 // Add has the property that adding any two 2's complement numbers can only
2054 // have one carry bit which can change a sign. As such, if LHS and RHS each
2055 // have at least two sign bits, we know that the addition of the two values will
2056 // sign extend fine.
2057 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2058 return true;
2059
2060
2061 // If one of the operands only has one non-zero bit, and if the other operand
2062 // has a known-zero bit in a more significant place than it (not including the
2063 // sign bit) the ripple may go up to and fill the zero, but won't change the
2064 // sign. For example, (X & ~4) + 1.
2065
2066 // TODO: Implement.
2067
2068 return false;
2069}
2070
Chris Lattner2454a2e2008-01-29 06:52:45 +00002071
Chris Lattner7e708292002-06-25 16:13:24 +00002072Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002073 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002074 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002075
Chris Lattner66331a42004-04-10 22:01:55 +00002076 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002077 // X + undef -> undef
2078 if (isa<UndefValue>(RHS))
2079 return ReplaceInstUsesWith(I, RHS);
2080
Chris Lattner66331a42004-04-10 22:01:55 +00002081 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002082 if (RHSC->isNullValue())
2083 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002084
Chris Lattner66331a42004-04-10 22:01:55 +00002085 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002086 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002087 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002088 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002089 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002090 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002091
2092 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2093 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002094 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002095 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002096
Eli Friedman709b33d2009-07-13 22:27:52 +00002097 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002098 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Eli Friedman709b33d2009-07-13 22:27:52 +00002099 if (ZI->getSrcTy() == Type::Int1Ty)
2100 return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002101 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002102
2103 if (isa<PHINode>(LHS))
2104 if (Instruction *NV = FoldOpIntoPhi(I))
2105 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002106
Chris Lattner4f637d42006-01-06 17:59:59 +00002107 ConstantInt *XorRHS = 0;
2108 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002109 if (isa<ConstantInt>(RHSC) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002110 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002111 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002112 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002113
Zhou Sheng4351c642007-04-02 08:20:41 +00002114 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002115 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2116 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002117 do {
2118 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002119 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2120 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002121 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2122 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002123 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002124 if (!MaskedValueIsZero(XorLHS,
2125 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002126 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002127 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002128 }
2129 }
2130 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002131 C0080Val = APIntOps::lshr(C0080Val, Size);
2132 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2133 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002134
Reid Spencer35c38852007-03-28 01:36:16 +00002135 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002136 // with funny bit widths then this switch statement should be removed. It
2137 // is just here to get the size of the "middle" type back up to something
2138 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002139 const Type *MiddleType = 0;
2140 switch (Size) {
2141 default: break;
2142 case 32: MiddleType = Type::Int32Ty; break;
2143 case 16: MiddleType = Type::Int16Ty; break;
2144 case 8: MiddleType = Type::Int8Ty; break;
2145 }
2146 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002147 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002148 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002149 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002150 }
2151 }
Chris Lattner66331a42004-04-10 22:01:55 +00002152 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002153
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002154 if (I.getType() == Type::Int1Ty)
2155 return BinaryOperator::CreateXor(LHS, RHS);
2156
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002157 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002158 if (I.getType()->isInteger()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002159 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2160 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002161
2162 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2163 if (RHSI->getOpcode() == Instruction::Sub)
2164 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2165 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2166 }
2167 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2168 if (LHSI->getOpcode() == Instruction::Sub)
2169 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2170 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2171 }
Robert Bocchino71698282004-07-27 21:02:21 +00002172 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002173
Chris Lattner5c4afb92002-05-08 22:46:53 +00002174 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002175 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002176 if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002177 if (LHS->getType()->isIntOrIntVector()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002178 if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002179 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002180 InsertNewInstBefore(NewAdd, I);
Owen Anderson0a5372e2009-07-13 04:09:18 +00002181 return BinaryOperator::CreateNeg(*Context, NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002182 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002183 }
2184
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002185 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002186 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002187
2188 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002189 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002190 if (Value *V = dyn_castNegVal(RHS, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002191 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002192
Misha Brukmanfd939082005-04-21 23:48:37 +00002193
Chris Lattner50af16a2004-11-13 19:50:12 +00002194 ConstantInt *C2;
Owen Andersond672ecb2009-07-03 00:17:18 +00002195 if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002196 if (X == RHS) // X*C + X --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002197 return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002198
2199 // X*C1 + X*C2 --> X * (C1+C2)
2200 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002201 if (X == dyn_castFoldableMul(RHS, C1, Context))
2202 return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002203 }
2204
2205 // X + X*C --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002206 if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2207 return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002208
Chris Lattnere617c9e2007-01-05 02:17:46 +00002209 // X + ~X --> -1 since ~X = -X-1
Owen Andersond672ecb2009-07-03 00:17:18 +00002210 if (dyn_castNotVal(LHS, Context) == RHS ||
2211 dyn_castNotVal(RHS, Context) == LHS)
2212 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002213
Chris Lattnerad3448c2003-02-18 19:57:07 +00002214
Chris Lattner564a7272003-08-13 19:01:45 +00002215 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002216 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002217 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002218 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002219
2220 // A+B --> A|B iff A and B have no bits set in common.
2221 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2222 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2223 APInt LHSKnownOne(IT->getBitWidth(), 0);
2224 APInt LHSKnownZero(IT->getBitWidth(), 0);
2225 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2226 if (LHSKnownZero != 0) {
2227 APInt RHSKnownOne(IT->getBitWidth(), 0);
2228 APInt RHSKnownZero(IT->getBitWidth(), 0);
2229 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2230
2231 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002232 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002233 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002234 }
2235 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002236
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002237 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002238 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002239 Value *W, *X, *Y, *Z;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002240 if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2241 match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002242 if (W != Y) {
2243 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002244 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002245 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002246 std::swap(W, X);
2247 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002248 std::swap(Y, Z);
2249 std::swap(W, X);
2250 }
2251 }
2252
2253 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002254 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002255 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002256 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002257 }
2258 }
2259 }
2260
Chris Lattner6b032052003-10-02 15:11:26 +00002261 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002262 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002263 if (match(LHS, m_Not(m_Value(X)), *Context)) // ~X + C --> (C-1) - X
Owen Andersond672ecb2009-07-03 00:17:18 +00002264 return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002265
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002266 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002267 if (LHS->hasOneUse() &&
2268 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002269 Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002270 if (Anded == CRHS) {
2271 // See if all bits from the first bit set in the Add RHS up are included
2272 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002273 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002274
2275 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002276 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002277
2278 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002279 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002280
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002281 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2282 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002283 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002284 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002285 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002286 }
2287 }
2288 }
2289
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002290 // Try to fold constant add into select arguments.
2291 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002292 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002293 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002294 }
2295
Reid Spencer1628cec2006-10-26 06:15:43 +00002296 // add (cast *A to intptrtype) B ->
Dan Gohmana119de82009-06-14 23:30:43 +00002297 // cast (GEP (cast *A to i8*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002298 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002299 CastInst *CI = dyn_cast<CastInst>(LHS);
2300 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002301 if (!CI) {
2302 CI = dyn_cast<CastInst>(RHS);
2303 Other = LHS;
2304 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002305 if (CI && CI->getType()->isSized() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00002306 (CI->getType()->getScalarSizeInBits() ==
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002307 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002308 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002309 unsigned AS =
2310 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002311 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002312 Context->getPointerType(Type::Int8Ty, AS), I);
Dan Gohman3a7a68c2009-07-17 22:25:10 +00002313 GetElementPtrInst *GEP = GetElementPtrInst::Create(I2, Other, "ctg2");
2314 // A GEP formed from an arbitrary add may overflow.
2315 cast<GEPOperator>(GEP)->setHasNoPointerOverflow(false);
2316 I2 = InsertNewInstBefore(GEP, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002317 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002318 }
2319 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002320
Chris Lattner42790482007-12-20 01:56:58 +00002321 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002322 {
2323 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002324 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002325 if (!SI) {
2326 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002327 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002328 }
Chris Lattner42790482007-12-20 01:56:58 +00002329 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002330 Value *TV = SI->getTrueValue();
2331 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002332 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002333
2334 // Can we fold the add into the argument of the select?
2335 // We check both true and false select arguments for a matching subtract.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002336 if (match(FV, m_Zero(), *Context) &&
2337 match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002338 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002339 return SelectInst::Create(SI->getCondition(), N, A);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002340 if (match(TV, m_Zero(), *Context) &&
2341 match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002342 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002343 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002344 }
2345 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002346
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002347 // Check for (add (sext x), y), see if we can merge this into an
2348 // integer add followed by a sext.
2349 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2350 // (add (sext x), cst) --> (sext (add x, cst'))
2351 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2352 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002353 Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002354 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002355 Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002356 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2357 // Insert the new, smaller add.
2358 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2359 CI, "addconv");
2360 InsertNewInstBefore(NewAdd, I);
2361 return new SExtInst(NewAdd, I.getType());
2362 }
2363 }
2364
2365 // (add (sext x), (sext y)) --> (sext (add int x, y))
2366 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2367 // Only do this if x/y have the same type, if at last one of them has a
2368 // single use (so we don't increase the number of sexts), and if the
2369 // integer add will not overflow.
2370 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2371 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2372 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2373 RHSConv->getOperand(0))) {
2374 // Insert the new integer add.
2375 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2376 RHSConv->getOperand(0),
2377 "addconv");
2378 InsertNewInstBefore(NewAdd, I);
2379 return new SExtInst(NewAdd, I.getType());
2380 }
2381 }
2382 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002383
2384 return Changed ? &I : 0;
2385}
2386
2387Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2388 bool Changed = SimplifyCommutative(I);
2389 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2390
2391 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2392 // X + 0 --> X
2393 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002394 if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002395 (I.getType())->getValueAPF()))
2396 return ReplaceInstUsesWith(I, LHS);
2397 }
2398
2399 if (isa<PHINode>(LHS))
2400 if (Instruction *NV = FoldOpIntoPhi(I))
2401 return NV;
2402 }
2403
2404 // -A + B --> B - A
2405 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002406 if (Value *LHSV = dyn_castFNegVal(LHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002407 return BinaryOperator::CreateFSub(RHS, LHSV);
2408
2409 // A + -B --> A - B
2410 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002411 if (Value *V = dyn_castFNegVal(RHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002412 return BinaryOperator::CreateFSub(LHS, V);
2413
2414 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2415 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2416 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2417 return ReplaceInstUsesWith(I, LHS);
2418
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002419 // Check for (add double (sitofp x), y), see if we can merge this into an
2420 // integer add followed by a promotion.
2421 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2422 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2423 // ... if the constant fits in the integer value. This is useful for things
2424 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2425 // requires a constant pool load, and generally allows the add to be better
2426 // instcombined.
2427 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2428 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002429 Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002430 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002431 Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002432 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2433 // Insert the new integer add.
2434 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2435 CI, "addconv");
2436 InsertNewInstBefore(NewAdd, I);
2437 return new SIToFPInst(NewAdd, I.getType());
2438 }
2439 }
2440
2441 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2442 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2443 // Only do this if x/y have the same type, if at last one of them has a
2444 // single use (so we don't increase the number of int->fp conversions),
2445 // and if the integer add will not overflow.
2446 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2447 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2448 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2449 RHSConv->getOperand(0))) {
2450 // Insert the new integer add.
2451 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2452 RHSConv->getOperand(0),
2453 "addconv");
2454 InsertNewInstBefore(NewAdd, I);
2455 return new SIToFPInst(NewAdd, I.getType());
2456 }
2457 }
2458 }
2459
Chris Lattner7e708292002-06-25 16:13:24 +00002460 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002461}
2462
Chris Lattner7e708292002-06-25 16:13:24 +00002463Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002464 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002465
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002466 if (Op0 == Op1) // sub X, X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002467 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002468
Chris Lattner233f7dc2002-08-12 21:17:25 +00002469 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002470 if (Value *V = dyn_castNegVal(Op1, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002471 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002472
Chris Lattnere87597f2004-10-16 18:11:37 +00002473 if (isa<UndefValue>(Op0))
2474 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2475 if (isa<UndefValue>(Op1))
2476 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2477
Chris Lattnerd65460f2003-11-05 01:06:05 +00002478 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2479 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002480 if (C->isAllOnesValue())
Owen Anderson73c6b712009-07-13 20:58:05 +00002481 return BinaryOperator::CreateNot(*Context, Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002482
Chris Lattnerd65460f2003-11-05 01:06:05 +00002483 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002484 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002485 if (match(Op1, m_Not(m_Value(X)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002486 return BinaryOperator::CreateAdd(X, AddOne(C, Context));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002487
Chris Lattner76b7a062007-01-15 07:02:54 +00002488 // -(X >>u 31) -> (X >>s 31)
2489 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002490 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002491 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002492 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002493 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002494 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002495 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002496 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002497 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002498 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002499 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002500 }
2501 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002502 }
2503 else if (SI->getOpcode() == Instruction::AShr) {
2504 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2505 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002506 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002507 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002508 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002509 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002510 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002511 }
2512 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002513 }
2514 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002515 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002516
2517 // Try to fold constant sub into select arguments.
2518 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002519 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002520 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002521
2522 // C - zext(bool) -> bool ? C - 1 : C
2523 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2524 if (ZI->getSrcTy() == Type::Int1Ty)
2525 return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002526 }
2527
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002528 if (I.getType() == Type::Int1Ty)
2529 return BinaryOperator::CreateXor(Op0, Op1);
2530
Chris Lattner43d84d62005-04-07 16:15:25 +00002531 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002532 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002533 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002534 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2535 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002536 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002537 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0),
2538 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002539 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2540 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2541 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002542 return BinaryOperator::CreateSub(
2543 Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002544 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002545 }
2546
Chris Lattnerfd059242003-10-15 16:48:29 +00002547 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002548 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2549 // is not used by anyone else...
2550 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002551 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002552 // Swap the two operands of the subexpr...
2553 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2554 Op1I->setOperand(0, IIOp1);
2555 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002556
Chris Lattnera2881962003-02-18 19:28:33 +00002557 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002558 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002559 }
2560
2561 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2562 //
2563 if (Op1I->getOpcode() == Instruction::And &&
2564 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2565 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2566
Chris Lattnerf523d062004-06-09 05:08:07 +00002567 Value *NewNot =
Owen Anderson73c6b712009-07-13 20:58:05 +00002568 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
2569 OtherOp, "B.not"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002570 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002571 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002572
Reid Spencerac5209e2006-10-16 23:08:08 +00002573 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002574 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002575 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002576 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002577 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002578 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002579 Context->getConstantExprNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002580
Chris Lattnerad3448c2003-02-18 19:57:07 +00002581 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002582 ConstantInt *C2 = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00002583 if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2584 Constant *CP1 =
2585 Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002586 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002587 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002588 }
Chris Lattner40371712002-05-09 01:29:19 +00002589 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002590 }
Chris Lattnera2881962003-02-18 19:28:33 +00002591
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002592 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2593 if (Op0I->getOpcode() == Instruction::Add) {
2594 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2595 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2596 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2597 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2598 } else if (Op0I->getOpcode() == Instruction::Sub) {
2599 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002600 return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2601 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002602 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002603 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002604
Chris Lattner50af16a2004-11-13 19:50:12 +00002605 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002606 if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002607 if (X == Op1) // X*C - X --> X * (C-1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002608 return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002609
Chris Lattner50af16a2004-11-13 19:50:12 +00002610 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Owen Andersond672ecb2009-07-03 00:17:18 +00002611 if (X == dyn_castFoldableMul(Op1, C2, Context))
2612 return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002613 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002614 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002615}
2616
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002617Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2618 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2619
2620 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002621 if (Value *V = dyn_castFNegVal(Op1, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002622 return BinaryOperator::CreateFAdd(Op0, V);
2623
2624 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2625 if (Op1I->getOpcode() == Instruction::FAdd) {
2626 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002627 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2628 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002629 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002630 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2631 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002632 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002633 }
2634
2635 return 0;
2636}
2637
Chris Lattnera0141b92007-07-15 20:42:37 +00002638/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2639/// comparison only checks the sign bit. If it only checks the sign bit, set
2640/// TrueIfSigned if the result of the comparison is true when the input value is
2641/// signed.
2642static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2643 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002644 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002645 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2646 TrueIfSigned = true;
2647 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002648 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2649 TrueIfSigned = true;
2650 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002651 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2652 TrueIfSigned = false;
2653 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002654 case ICmpInst::ICMP_UGT:
2655 // True if LHS u> RHS and RHS == high-bit-mask - 1
2656 TrueIfSigned = true;
2657 return RHS->getValue() ==
2658 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2659 case ICmpInst::ICMP_UGE:
2660 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2661 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002662 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002663 default:
2664 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002665 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002666}
2667
Chris Lattner7e708292002-06-25 16:13:24 +00002668Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002669 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002670 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002671
Dan Gohman77b81fe2009-06-04 17:12:12 +00002672 // TODO: If Op1 is undef and Op0 is finite, return zero.
2673 if (!I.getType()->isFPOrFPVector() &&
2674 isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002675 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002676
Chris Lattner233f7dc2002-08-12 21:17:25 +00002677 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002678 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2679 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002680
2681 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002682 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002683 if (SI->getOpcode() == Instruction::Shl)
2684 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002685 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002686 Context->getConstantExprShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002687
Zhou Sheng843f07672007-04-19 05:39:12 +00002688 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002689 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2690 if (CI->equalsInt(1)) // X * 1 == X
2691 return ReplaceInstUsesWith(I, Op0);
2692 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002693 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002694
Zhou Sheng97b52c22007-03-29 01:57:21 +00002695 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002696 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002697 return BinaryOperator::CreateShl(Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00002698 Context->getConstantInt(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002699 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002700 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002701 if (Op1->isNullValue())
2702 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002703
2704 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2705 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002706 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002707
2708 // As above, vector X*splat(1.0) -> X in all defined cases.
2709 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002710 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2711 if (CI->equalsInt(1))
2712 return ReplaceInstUsesWith(I, Op0);
2713 }
2714 }
Chris Lattnera2881962003-02-18 19:28:33 +00002715 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002716
2717 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2718 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002719 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002720 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002721 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002722 Op1, "tmp");
2723 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00002724 Value *C1C2 = Context->getConstantExprMul(Op1,
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002725 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002726 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002727
2728 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002729
2730 // Try to fold constant mul into select arguments.
2731 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002732 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002733 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002734
2735 if (isa<PHINode>(Op0))
2736 if (Instruction *NV = FoldOpIntoPhi(I))
2737 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002738 }
2739
Owen Andersond672ecb2009-07-03 00:17:18 +00002740 if (Value *Op0v = dyn_castNegVal(Op0, Context)) // -X * -Y = X*Y
2741 if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002742 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002743
Nick Lewycky0c730792008-11-21 07:33:58 +00002744 // (X / Y) * Y = X - (X % Y)
2745 // (X / Y) * -Y = (X % Y) - X
2746 {
2747 Value *Op1 = I.getOperand(1);
2748 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2749 if (!BO ||
2750 (BO->getOpcode() != Instruction::UDiv &&
2751 BO->getOpcode() != Instruction::SDiv)) {
2752 Op1 = Op0;
2753 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2754 }
Owen Andersond672ecb2009-07-03 00:17:18 +00002755 Value *Neg = dyn_castNegVal(Op1, Context);
Nick Lewycky0c730792008-11-21 07:33:58 +00002756 if (BO && BO->hasOneUse() &&
2757 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2758 (BO->getOpcode() == Instruction::UDiv ||
2759 BO->getOpcode() == Instruction::SDiv)) {
2760 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2761
2762 Instruction *Rem;
2763 if (BO->getOpcode() == Instruction::UDiv)
2764 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2765 else
2766 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2767
2768 InsertNewInstBefore(Rem, I);
2769 Rem->takeName(BO);
2770
2771 if (Op1BO == Op1)
2772 return BinaryOperator::CreateSub(Op0BO, Rem);
2773 else
2774 return BinaryOperator::CreateSub(Rem, Op0BO);
2775 }
2776 }
2777
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002778 if (I.getType() == Type::Int1Ty)
2779 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2780
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002781 // If one of the operands of the multiply is a cast from a boolean value, then
2782 // we know the bool is either zero or one, so this is a 'masking' multiply.
2783 // See if we can simplify things based on how the boolean was originally
2784 // formed.
2785 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002786 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002787 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002788 BoolCast = CI;
2789 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002790 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002791 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002792 BoolCast = CI;
2793 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002794 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002795 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2796 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002797 bool TIS = false;
2798
Reid Spencere4d87aa2006-12-23 06:05:41 +00002799 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002800 // multiply into a shift/and combination.
2801 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002802 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2803 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002804 // Shift the X value right to turn it into "all signbits".
Owen Andersond672ecb2009-07-03 00:17:18 +00002805 Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002806 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002807 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002808 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002809 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002810 BoolCast->getOperand(0)->getName()+
2811 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002812
2813 // If the multiply type is not the same as the source type, sign extend
2814 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002815 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002816 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2817 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002818 Instruction::CastOps opcode =
2819 (SrcBits == DstBits ? Instruction::BitCast :
2820 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2821 V = InsertCastBefore(opcode, V, I.getType(), I);
2822 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002823
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002824 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002825 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002826 }
2827 }
2828 }
2829
Chris Lattner7e708292002-06-25 16:13:24 +00002830 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002831}
2832
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002833Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2834 bool Changed = SimplifyCommutative(I);
2835 Value *Op0 = I.getOperand(0);
2836
2837 // Simplify mul instructions with a constant RHS...
2838 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2839 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2840 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2841 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2842 if (Op1F->isExactlyValue(1.0))
2843 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2844 } else if (isa<VectorType>(Op1->getType())) {
2845 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2846 // As above, vector X*splat(1.0) -> X in all defined cases.
2847 if (Constant *Splat = Op1V->getSplatValue()) {
2848 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2849 if (F->isExactlyValue(1.0))
2850 return ReplaceInstUsesWith(I, Op0);
2851 }
2852 }
2853 }
2854
2855 // Try to fold constant mul into select arguments.
2856 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2857 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2858 return R;
2859
2860 if (isa<PHINode>(Op0))
2861 if (Instruction *NV = FoldOpIntoPhi(I))
2862 return NV;
2863 }
2864
Owen Andersond672ecb2009-07-03 00:17:18 +00002865 if (Value *Op0v = dyn_castFNegVal(Op0, Context)) // -X * -Y = X*Y
2866 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002867 return BinaryOperator::CreateFMul(Op0v, Op1v);
2868
2869 return Changed ? &I : 0;
2870}
2871
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002872/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2873/// instruction.
2874bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2875 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2876
2877 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2878 int NonNullOperand = -1;
2879 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2880 if (ST->isNullValue())
2881 NonNullOperand = 2;
2882 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2883 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2884 if (ST->isNullValue())
2885 NonNullOperand = 1;
2886
2887 if (NonNullOperand == -1)
2888 return false;
2889
2890 Value *SelectCond = SI->getOperand(0);
2891
2892 // Change the div/rem to use 'Y' instead of the select.
2893 I.setOperand(1, SI->getOperand(NonNullOperand));
2894
2895 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2896 // problem. However, the select, or the condition of the select may have
2897 // multiple uses. Based on our knowledge that the operand must be non-zero,
2898 // propagate the known value for the select into other uses of it, and
2899 // propagate a known value of the condition into its other users.
2900
2901 // If the select and condition only have a single use, don't bother with this,
2902 // early exit.
2903 if (SI->use_empty() && SelectCond->hasOneUse())
2904 return true;
2905
2906 // Scan the current block backward, looking for other uses of SI.
2907 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2908
2909 while (BBI != BBFront) {
2910 --BBI;
2911 // If we found a call to a function, we can't assume it will return, so
2912 // information from below it cannot be propagated above it.
2913 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2914 break;
2915
2916 // Replace uses of the select or its condition with the known values.
2917 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2918 I != E; ++I) {
2919 if (*I == SI) {
2920 *I = SI->getOperand(NonNullOperand);
2921 AddToWorkList(BBI);
2922 } else if (*I == SelectCond) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002923 *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2924 Context->getConstantIntFalse();
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002925 AddToWorkList(BBI);
2926 }
2927 }
2928
2929 // If we past the instruction, quit looking for it.
2930 if (&*BBI == SI)
2931 SI = 0;
2932 if (&*BBI == SelectCond)
2933 SelectCond = 0;
2934
2935 // If we ran out of things to eliminate, break out of the loop.
2936 if (SelectCond == 0 && SI == 0)
2937 break;
2938
2939 }
2940 return true;
2941}
2942
2943
Reid Spencer1628cec2006-10-26 06:15:43 +00002944/// This function implements the transforms on div instructions that work
2945/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2946/// used by the visitors to those instructions.
2947/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002948Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002949 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002950
Chris Lattner50b2ca42008-02-19 06:12:18 +00002951 // undef / X -> 0 for integer.
2952 // undef / X -> undef for FP (the undef could be a snan).
2953 if (isa<UndefValue>(Op0)) {
2954 if (Op0->getType()->isFPOrFPVector())
2955 return ReplaceInstUsesWith(I, Op0);
Owen Andersond672ecb2009-07-03 00:17:18 +00002956 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002957 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002958
2959 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002960 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002961 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002962
Reid Spencer1628cec2006-10-26 06:15:43 +00002963 return 0;
2964}
Misha Brukmanfd939082005-04-21 23:48:37 +00002965
Reid Spencer1628cec2006-10-26 06:15:43 +00002966/// This function implements the transforms common to both integer division
2967/// instructions (udiv and sdiv). It is called by the visitors to those integer
2968/// division instructions.
2969/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002970Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002971 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2972
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002973 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002974 if (Op0 == Op1) {
2975 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002976 Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002977 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00002978 return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002979 }
2980
Owen Andersond672ecb2009-07-03 00:17:18 +00002981 Constant *CI = Context->getConstantInt(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002982 return ReplaceInstUsesWith(I, CI);
2983 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002984
Reid Spencer1628cec2006-10-26 06:15:43 +00002985 if (Instruction *Common = commonDivTransforms(I))
2986 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002987
2988 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2989 // This does not apply for fdiv.
2990 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2991 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002992
2993 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2994 // div X, 1 == X
2995 if (RHS->equalsInt(1))
2996 return ReplaceInstUsesWith(I, Op0);
2997
2998 // (X / C1) / C2 -> X / (C1*C2)
2999 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3000 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3001 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003002 if (MultiplyOverflows(RHS, LHSRHS,
3003 I.getOpcode()==Instruction::SDiv, Context))
3004 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003005 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003006 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00003007 Context->getConstantExprMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003008 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003009
Reid Spencerbca0e382007-03-23 20:05:17 +00003010 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003011 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3012 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3013 return R;
3014 if (isa<PHINode>(Op0))
3015 if (Instruction *NV = FoldOpIntoPhi(I))
3016 return NV;
3017 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003018 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003019
Chris Lattnera2881962003-02-18 19:28:33 +00003020 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003021 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003022 if (LHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00003023 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003024
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003025 // It can't be division by zero, hence it must be division by one.
3026 if (I.getType() == Type::Int1Ty)
3027 return ReplaceInstUsesWith(I, Op0);
3028
Nick Lewycky895f0852008-11-27 20:21:08 +00003029 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3030 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3031 // div X, 1 == X
3032 if (X->isOne())
3033 return ReplaceInstUsesWith(I, Op0);
3034 }
3035
Reid Spencer1628cec2006-10-26 06:15:43 +00003036 return 0;
3037}
3038
3039Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3040 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3041
3042 // Handle the integer div common cases
3043 if (Instruction *Common = commonIDivTransforms(I))
3044 return Common;
3045
Reid Spencer1628cec2006-10-26 06:15:43 +00003046 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003047 // X udiv C^2 -> X >> C
3048 // Check to see if this is an unsigned division with an exact power of 2,
3049 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003050 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003051 return BinaryOperator::CreateLShr(Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00003052 Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003053
3054 // X udiv C, where C >= signbit
3055 if (C->getValue().isNegative()) {
Owen Anderson333c4002009-07-09 23:48:35 +00003056 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3057 ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky8ca52482008-11-27 22:41:10 +00003058 I);
Owen Andersond672ecb2009-07-03 00:17:18 +00003059 return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3060 Context->getConstantInt(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003061 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003062 }
3063
3064 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003065 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003066 if (RHSI->getOpcode() == Instruction::Shl &&
3067 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003068 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003069 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003070 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003071 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003072 if (uint32_t C2 = C1.logBase2()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003073 Constant *C2V = Context->getConstantInt(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003074 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003075 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003076 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003077 }
3078 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003079 }
3080
Reid Spencer1628cec2006-10-26 06:15:43 +00003081 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3082 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003083 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003084 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003085 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003086 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003087 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003088 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003089 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003090 // Construct the "on true" case of the select
Owen Andersond672ecb2009-07-03 00:17:18 +00003091 Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003092 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003093 Op0, TC, SI->getName()+".t");
3094 TSI = InsertNewInstBefore(TSI, I);
3095
3096 // Construct the "on false" case of the select
Owen Andersond672ecb2009-07-03 00:17:18 +00003097 Constant *FC = Context->getConstantInt(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003098 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003099 Op0, FC, SI->getName()+".f");
3100 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003101
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003102 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003103 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003104 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003105 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003106 return 0;
3107}
3108
Reid Spencer1628cec2006-10-26 06:15:43 +00003109Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3110 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3111
3112 // Handle the integer div common cases
3113 if (Instruction *Common = commonIDivTransforms(I))
3114 return Common;
3115
3116 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3117 // sdiv X, -1 == -X
3118 if (RHS->isAllOnesValue())
Owen Anderson0a5372e2009-07-13 04:09:18 +00003119 return BinaryOperator::CreateNeg(*Context, Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003120 }
3121
3122 // If the sign bits of both operands are zero (i.e. we can prove they are
3123 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003124 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003125 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003126 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003127 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003128 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003129 }
3130 }
3131
3132 return 0;
3133}
3134
3135Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3136 return commonDivTransforms(I);
3137}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003138
Reid Spencer0a783f72006-11-02 01:53:59 +00003139/// This function implements the transforms on rem instructions that work
3140/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3141/// is used by the visitors to those instructions.
3142/// @brief Transforms common to all three rem instructions
3143Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003144 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003145
Chris Lattner50b2ca42008-02-19 06:12:18 +00003146 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3147 if (I.getType()->isFPOrFPVector())
3148 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersond672ecb2009-07-03 00:17:18 +00003149 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003150 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003151 if (isa<UndefValue>(Op1))
3152 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003153
3154 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003155 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3156 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003157
Reid Spencer0a783f72006-11-02 01:53:59 +00003158 return 0;
3159}
3160
3161/// This function implements the transforms common to both integer remainder
3162/// instructions (urem and srem). It is called by the visitors to those integer
3163/// remainder instructions.
3164/// @brief Common integer remainder transforms
3165Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3166 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3167
3168 if (Instruction *common = commonRemTransforms(I))
3169 return common;
3170
Dale Johannesened6af242009-01-21 00:35:19 +00003171 // 0 % X == 0 for integer, we don't need to preserve faults!
3172 if (Constant *LHS = dyn_cast<Constant>(Op0))
3173 if (LHS->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00003174 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003175
Chris Lattner857e8cd2004-12-12 21:48:58 +00003176 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003177 // X % 0 == undef, we don't need to preserve faults!
3178 if (RHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00003179 return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003180
Chris Lattnera2881962003-02-18 19:28:33 +00003181 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003182 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003183
Chris Lattner97943922006-02-28 05:49:21 +00003184 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3185 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3186 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3187 return R;
3188 } else if (isa<PHINode>(Op0I)) {
3189 if (Instruction *NV = FoldOpIntoPhi(I))
3190 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003191 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003192
3193 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003194 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003195 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003196 }
Chris Lattnera2881962003-02-18 19:28:33 +00003197 }
3198
Reid Spencer0a783f72006-11-02 01:53:59 +00003199 return 0;
3200}
3201
3202Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3203 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3204
3205 if (Instruction *common = commonIRemTransforms(I))
3206 return common;
3207
3208 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3209 // X urem C^2 -> X and C
3210 // Check to see if this is an unsigned remainder with an exact power of 2,
3211 // if so, convert to a bitwise and.
3212 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003213 if (C->getValue().isPowerOf2())
Owen Andersond672ecb2009-07-03 00:17:18 +00003214 return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
Reid Spencer0a783f72006-11-02 01:53:59 +00003215 }
3216
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003217 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003218 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3219 if (RHSI->getOpcode() == Instruction::Shl &&
3220 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003221 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Anderson73c6b712009-07-13 20:58:05 +00003222 Constant *N1 = Context->getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003223 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003224 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003225 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003226 }
3227 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003228 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003229
Reid Spencer0a783f72006-11-02 01:53:59 +00003230 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3231 // where C1&C2 are powers of two.
3232 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3233 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3234 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3235 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003236 if ((STO->getValue().isPowerOf2()) &&
3237 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003238 Value *TrueAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003239 BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3240 SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003241 Value *FalseAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003242 BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3243 SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003244 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003245 }
3246 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003247 }
3248
Chris Lattner3f5b8772002-05-06 16:14:14 +00003249 return 0;
3250}
3251
Reid Spencer0a783f72006-11-02 01:53:59 +00003252Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3253 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3254
Dan Gohmancff55092007-11-05 23:16:33 +00003255 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003256 if (Instruction *common = commonIRemTransforms(I))
3257 return common;
3258
Owen Andersond672ecb2009-07-03 00:17:18 +00003259 if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
Nick Lewycky23c04302008-09-03 06:24:21 +00003260 if (!isa<Constant>(RHSNeg) ||
3261 (isa<ConstantInt>(RHSNeg) &&
3262 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003263 // X % -Y -> X % Y
3264 AddUsesToWorkList(I);
3265 I.setOperand(1, RHSNeg);
3266 return &I;
3267 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003268
Dan Gohmancff55092007-11-05 23:16:33 +00003269 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003270 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003271 if (I.getType()->isInteger()) {
3272 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3273 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3274 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003275 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003276 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003277 }
3278
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003279 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003280 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3281 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003282
Nick Lewycky9dce8732008-12-20 16:48:00 +00003283 bool hasNegative = false;
3284 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3285 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3286 if (RHS->getValue().isNegative())
3287 hasNegative = true;
3288
3289 if (hasNegative) {
3290 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003291 for (unsigned i = 0; i != VWidth; ++i) {
3292 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3293 if (RHS->getValue().isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00003294 Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003295 else
3296 Elts[i] = RHS;
3297 }
3298 }
3299
Owen Andersond672ecb2009-07-03 00:17:18 +00003300 Constant *NewRHSV = Context->getConstantVector(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003301 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003302 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003303 I.setOperand(1, NewRHSV);
3304 return &I;
3305 }
3306 }
3307 }
3308
Reid Spencer0a783f72006-11-02 01:53:59 +00003309 return 0;
3310}
3311
3312Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003313 return commonRemTransforms(I);
3314}
3315
Chris Lattner457dd822004-06-09 07:59:58 +00003316// isOneBitSet - Return true if there is exactly one bit set in the specified
3317// constant.
3318static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003319 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003320}
3321
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003322// isHighOnes - Return true if the constant is of the form 1+0+.
3323// This is the same as lowones(~X).
3324static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003325 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003326}
3327
Reid Spencere4d87aa2006-12-23 06:05:41 +00003328/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003329/// are carefully arranged to allow folding of expressions such as:
3330///
3331/// (A < B) | (A > B) --> (A != B)
3332///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003333/// Note that this is only valid if the first and second predicates have the
3334/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003335///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003336/// Three bits are used to represent the condition, as follows:
3337/// 0 A > B
3338/// 1 A == B
3339/// 2 A < B
3340///
3341/// <=> Value Definition
3342/// 000 0 Always false
3343/// 001 1 A > B
3344/// 010 2 A == B
3345/// 011 3 A >= B
3346/// 100 4 A < B
3347/// 101 5 A != B
3348/// 110 6 A <= B
3349/// 111 7 Always true
3350///
3351static unsigned getICmpCode(const ICmpInst *ICI) {
3352 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003353 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003354 case ICmpInst::ICMP_UGT: return 1; // 001
3355 case ICmpInst::ICMP_SGT: return 1; // 001
3356 case ICmpInst::ICMP_EQ: return 2; // 010
3357 case ICmpInst::ICMP_UGE: return 3; // 011
3358 case ICmpInst::ICMP_SGE: return 3; // 011
3359 case ICmpInst::ICMP_ULT: return 4; // 100
3360 case ICmpInst::ICMP_SLT: return 4; // 100
3361 case ICmpInst::ICMP_NE: return 5; // 101
3362 case ICmpInst::ICMP_ULE: return 6; // 110
3363 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003364 // True -> 7
3365 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003366 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003367 return 0;
3368 }
3369}
3370
Evan Cheng8db90722008-10-14 17:15:11 +00003371/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3372/// predicate into a three bit mask. It also returns whether it is an ordered
3373/// predicate by reference.
3374static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3375 isOrdered = false;
3376 switch (CC) {
3377 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3378 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003379 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3380 case FCmpInst::FCMP_UGT: return 1; // 001
3381 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3382 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003383 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3384 case FCmpInst::FCMP_UGE: return 3; // 011
3385 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3386 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003387 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3388 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003389 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3390 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003391 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003392 default:
3393 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003394 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003395 return 0;
3396 }
3397}
3398
Reid Spencere4d87aa2006-12-23 06:05:41 +00003399/// getICmpValue - This is the complement of getICmpCode, which turns an
3400/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003401/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003402/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003403static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003404 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003405 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003406 default: llvm_unreachable("Illegal ICmp code!");
Owen Andersond672ecb2009-07-03 00:17:18 +00003407 case 0: return Context->getConstantIntFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003408 case 1:
3409 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003410 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003411 else
Owen Anderson333c4002009-07-09 23:48:35 +00003412 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3413 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003414 case 3:
3415 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003416 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003417 else
Owen Anderson333c4002009-07-09 23:48:35 +00003418 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003419 case 4:
3420 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003421 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003422 else
Owen Anderson333c4002009-07-09 23:48:35 +00003423 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3424 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003425 case 6:
3426 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003427 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003428 else
Owen Anderson333c4002009-07-09 23:48:35 +00003429 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00003430 case 7: return Context->getConstantIntTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003431 }
3432}
3433
Evan Cheng8db90722008-10-14 17:15:11 +00003434/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3435/// opcode and two operands into either a FCmp instruction. isordered is passed
3436/// in to determine which kind of predicate to use in the new fcmp instruction.
3437static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003438 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003439 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003440 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003441 case 0:
3442 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003443 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003444 else
Owen Anderson333c4002009-07-09 23:48:35 +00003445 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003446 case 1:
3447 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003448 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003449 else
Owen Anderson333c4002009-07-09 23:48:35 +00003450 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003451 case 2:
3452 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003453 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003454 else
Owen Anderson333c4002009-07-09 23:48:35 +00003455 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003456 case 3:
3457 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003458 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003459 else
Owen Anderson333c4002009-07-09 23:48:35 +00003460 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003461 case 4:
3462 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003463 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003464 else
Owen Anderson333c4002009-07-09 23:48:35 +00003465 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003466 case 5:
3467 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003468 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003469 else
Owen Anderson333c4002009-07-09 23:48:35 +00003470 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003471 case 6:
3472 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003473 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003474 else
Owen Anderson333c4002009-07-09 23:48:35 +00003475 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00003476 case 7: return Context->getConstantIntTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003477 }
3478}
3479
Chris Lattnerb9553d62008-11-16 04:55:20 +00003480/// PredicatesFoldable - Return true if both predicates match sign or if at
3481/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003482static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3483 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003484 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3485 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003486}
3487
3488namespace {
3489// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3490struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003491 InstCombiner &IC;
3492 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003493 ICmpInst::Predicate pred;
3494 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3495 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3496 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003497 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003498 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3499 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003500 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3501 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003502 return false;
3503 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003504 Instruction *apply(Instruction &Log) const {
3505 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3506 if (ICI->getOperand(0) != LHS) {
3507 assert(ICI->getOperand(1) == LHS);
3508 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003509 }
3510
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003511 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003512 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003513 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003514 unsigned Code;
3515 switch (Log.getOpcode()) {
3516 case Instruction::And: Code = LHSCode & RHSCode; break;
3517 case Instruction::Or: Code = LHSCode | RHSCode; break;
3518 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003519 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003520 }
3521
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003522 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3523 ICmpInst::isSignedPredicate(ICI->getPredicate());
3524
Owen Andersond672ecb2009-07-03 00:17:18 +00003525 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003526 if (Instruction *I = dyn_cast<Instruction>(RV))
3527 return I;
3528 // Otherwise, it's a constant boolean value...
3529 return IC.ReplaceInstUsesWith(Log, RV);
3530 }
3531};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003532} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003533
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003534// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3535// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003536// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003537Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003538 ConstantInt *OpRHS,
3539 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003540 BinaryOperator &TheAnd) {
3541 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003542 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003543 if (!Op->isShift())
Owen Andersond672ecb2009-07-03 00:17:18 +00003544 Together = Context->getConstantExprAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003545
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003546 switch (Op->getOpcode()) {
3547 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003548 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003549 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003550 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003551 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003552 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003553 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003554 }
3555 break;
3556 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003557 if (Together == AndRHS) // (X | C) & C --> C
3558 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003559
Chris Lattner6e7ba452005-01-01 16:22:27 +00003560 if (Op->hasOneUse() && Together != OpRHS) {
3561 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003562 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003563 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003564 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003565 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003566 }
3567 break;
3568 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003569 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003570 // Adding a one to a single bit bit-field should be turned into an XOR
3571 // of the bit. First thing to check is to see if this AND is with a
3572 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003573 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003574
3575 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003576 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003577 // Ok, at this point, we know that we are masking the result of the
3578 // ADD down to exactly one bit. If the constant we are adding has
3579 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003580 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003581
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003582 // Check to see if any bits below the one bit set in AndRHSV are set.
3583 if ((AddRHS & (AndRHSV-1)) == 0) {
3584 // If not, the only thing that can effect the output of the AND is
3585 // the bit specified by AndRHSV. If that bit is set, the effect of
3586 // the XOR is to toggle the bit. If it is clear, then the ADD has
3587 // no effect.
3588 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3589 TheAnd.setOperand(0, X);
3590 return &TheAnd;
3591 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003592 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003593 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003594 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003595 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003596 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003597 }
3598 }
3599 }
3600 }
3601 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003602
3603 case Instruction::Shl: {
3604 // We know that the AND will not produce any of the bits shifted in, so if
3605 // the anded constant includes them, clear them now!
3606 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003607 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003608 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003609 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003610 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003611
Zhou Sheng290bec52007-03-29 08:15:12 +00003612 if (CI->getValue() == ShlMask) {
3613 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003614 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3615 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003616 TheAnd.setOperand(1, CI);
3617 return &TheAnd;
3618 }
3619 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003620 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003621 case Instruction::LShr:
3622 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003623 // We know that the AND will not produce any of the bits shifted in, so if
3624 // the anded constant includes them, clear them now! This only applies to
3625 // unsigned shifts, because a signed shr may bring in set bits!
3626 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003627 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003628 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003629 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003630 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003631
Zhou Sheng290bec52007-03-29 08:15:12 +00003632 if (CI->getValue() == ShrMask) {
3633 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003634 return ReplaceInstUsesWith(TheAnd, Op);
3635 } else if (CI != AndRHS) {
3636 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3637 return &TheAnd;
3638 }
3639 break;
3640 }
3641 case Instruction::AShr:
3642 // Signed shr.
3643 // See if this is shifting in some sign extension, then masking it out
3644 // with an and.
3645 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003646 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003647 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003648 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003649 Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003650 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003651 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003652 // Make the argument unsigned.
3653 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003654 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003655 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003656 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003657 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003658 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003659 }
3660 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003661 }
3662 return 0;
3663}
3664
Chris Lattner8b170942002-08-09 23:47:40 +00003665
Chris Lattnera96879a2004-09-29 17:40:11 +00003666/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3667/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003668/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3669/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003670/// insert new instructions.
3671Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003672 bool isSigned, bool Inside,
3673 Instruction &IB) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003674 assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003675 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003676 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003677
Chris Lattnera96879a2004-09-29 17:40:11 +00003678 if (Inside) {
3679 if (Lo == Hi) // Trivially false.
Owen Anderson333c4002009-07-09 23:48:35 +00003680 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003681
Reid Spencere4d87aa2006-12-23 06:05:41 +00003682 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003683 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003684 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003685 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Owen Anderson333c4002009-07-09 23:48:35 +00003686 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003687 }
3688
3689 // Emit V-Lo <u Hi-Lo
Owen Andersond672ecb2009-07-03 00:17:18 +00003690 Constant *NegLo = Context->getConstantExprNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003691 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003692 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003693 Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003694 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003695 }
3696
3697 if (Lo == Hi) // Trivially true.
Owen Anderson333c4002009-07-09 23:48:35 +00003698 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003699
Reid Spencere4e40032007-03-21 23:19:50 +00003700 // V < Min || V >= Hi -> V > Hi-1
Owen Andersond672ecb2009-07-03 00:17:18 +00003701 Hi = SubOne(cast<ConstantInt>(Hi), Context);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003702 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003703 ICmpInst::Predicate pred = (isSigned ?
3704 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Owen Anderson333c4002009-07-09 23:48:35 +00003705 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003706 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003707
Reid Spencere4e40032007-03-21 23:19:50 +00003708 // Emit V-Lo >u Hi-1-Lo
3709 // Note that Hi has already had one subtracted from it, above.
Owen Andersond672ecb2009-07-03 00:17:18 +00003710 ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003711 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003712 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003713 Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003714 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003715}
3716
Chris Lattner7203e152005-09-18 07:22:02 +00003717// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3718// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3719// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3720// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003721static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003722 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003723 uint32_t BitWidth = Val->getType()->getBitWidth();
3724 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003725
3726 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003727 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003728 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003729 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003730 return true;
3731}
3732
Chris Lattner7203e152005-09-18 07:22:02 +00003733/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3734/// where isSub determines whether the operator is a sub. If we can fold one of
3735/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003736///
3737/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3738/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3739/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3740///
3741/// return (A +/- B).
3742///
3743Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003744 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003745 Instruction &I) {
3746 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3747 if (!LHSI || LHSI->getNumOperands() != 2 ||
3748 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3749
3750 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3751
3752 switch (LHSI->getOpcode()) {
3753 default: return 0;
3754 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00003755 if (Context->getConstantExprAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003756 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003757 if ((Mask->getValue().countLeadingZeros() +
3758 Mask->getValue().countPopulation()) ==
3759 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003760 break;
3761
3762 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3763 // part, we don't need any explicit masks to take them out of A. If that
3764 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003765 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003766 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003767 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003768 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003769 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003770 break;
3771 }
3772 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003773 return 0;
3774 case Instruction::Or:
3775 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003776 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003777 if ((Mask->getValue().countLeadingZeros() +
3778 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersond672ecb2009-07-03 00:17:18 +00003779 && Context->getConstantExprAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003780 break;
3781 return 0;
3782 }
3783
3784 Instruction *New;
3785 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003786 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003787 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003788 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003789 return InsertNewInstBefore(New, I);
3790}
3791
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003792/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3793Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3794 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003795 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003796 ConstantInt *LHSCst, *RHSCst;
3797 ICmpInst::Predicate LHSCC, RHSCC;
3798
Chris Lattnerea065fb2008-11-16 05:10:52 +00003799 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003800 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3801 m_ConstantInt(LHSCst)), *Context) ||
3802 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3803 m_ConstantInt(RHSCst)), *Context))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003804 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003805
3806 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3807 // where C is a power of 2
3808 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3809 LHSCst->getValue().isPowerOf2()) {
3810 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3811 InsertNewInstBefore(NewOr, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003812 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003813 }
3814
3815 // From here on, we only handle:
3816 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3817 if (Val != Val2) return 0;
3818
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003819 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3820 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3821 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3822 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3823 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3824 return 0;
3825
3826 // We can't fold (ugt x, C) & (sgt x, C2).
3827 if (!PredicatesFoldable(LHSCC, RHSCC))
3828 return 0;
3829
3830 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003831 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003832 if (ICmpInst::isSignedPredicate(LHSCC) ||
3833 (ICmpInst::isEquality(LHSCC) &&
3834 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003835 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003836 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003837 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3838
3839 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003840 std::swap(LHS, RHS);
3841 std::swap(LHSCst, RHSCst);
3842 std::swap(LHSCC, RHSCC);
3843 }
3844
3845 // At this point, we know we have have two icmp instructions
3846 // comparing a value against two constants and and'ing the result
3847 // together. Because of the above check, we know that we only have
3848 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3849 // (from the FoldICmpLogical check above), that the two constants
3850 // are not equal and that the larger constant is on the RHS
3851 assert(LHSCst != RHSCst && "Compares not folded above?");
3852
3853 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003854 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003855 case ICmpInst::ICMP_EQ:
3856 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003857 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003858 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3859 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3860 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Andersond672ecb2009-07-03 00:17:18 +00003861 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003862 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3863 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3864 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3865 return ReplaceInstUsesWith(I, LHS);
3866 }
3867 case ICmpInst::ICMP_NE:
3868 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003869 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003870 case ICmpInst::ICMP_ULT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003871 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003872 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003873 break; // (X != 13 & X u< 15) -> no change
3874 case ICmpInst::ICMP_SLT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003875 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003876 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003877 break; // (X != 13 & X s< 15) -> no change
3878 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3879 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3880 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3881 return ReplaceInstUsesWith(I, RHS);
3882 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003883 if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3884 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003885 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3886 Val->getName()+".off");
3887 InsertNewInstBefore(Add, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003888 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
Owen Andersond672ecb2009-07-03 00:17:18 +00003889 Context->getConstantInt(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003890 }
3891 break; // (X != 13 & X != 15) -> no change
3892 }
3893 break;
3894 case ICmpInst::ICMP_ULT:
3895 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003896 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003897 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3898 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Andersond672ecb2009-07-03 00:17:18 +00003899 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003900 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3901 break;
3902 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3903 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3904 return ReplaceInstUsesWith(I, LHS);
3905 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3906 break;
3907 }
3908 break;
3909 case ICmpInst::ICMP_SLT:
3910 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003911 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003912 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3913 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Andersond672ecb2009-07-03 00:17:18 +00003914 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003915 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3916 break;
3917 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3918 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3919 return ReplaceInstUsesWith(I, LHS);
3920 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3921 break;
3922 }
3923 break;
3924 case ICmpInst::ICMP_UGT:
3925 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003926 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003927 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3928 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3929 return ReplaceInstUsesWith(I, RHS);
3930 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3931 break;
3932 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003933 if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003934 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003935 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003936 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003937 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3938 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003939 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3940 break;
3941 }
3942 break;
3943 case ICmpInst::ICMP_SGT:
3944 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003945 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003946 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3947 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3948 return ReplaceInstUsesWith(I, RHS);
3949 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3950 break;
3951 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003952 if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003953 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003954 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003955 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003956 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3957 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003958 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3959 break;
3960 }
3961 break;
3962 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003963
3964 return 0;
3965}
3966
3967
Chris Lattner7e708292002-06-25 16:13:24 +00003968Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003969 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003970 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003971
Chris Lattnere87597f2004-10-16 18:11:37 +00003972 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003973 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003974
Chris Lattner6e7ba452005-01-01 16:22:27 +00003975 // and X, X = X
3976 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003977 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003978
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003979 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003980 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00003981 if (SimplifyDemandedInstructionBits(I))
3982 return &I;
3983 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003984 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003985 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003986 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003987 } else if (isa<ConstantAggregateZero>(Op1)) {
3988 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003989 }
3990 }
Dan Gohman6de29f82009-06-15 22:12:54 +00003991
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003992 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003993 const APInt& AndRHSMask = AndRHS->getValue();
3994 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003995
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003996 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003997 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003998 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003999 Value *Op0LHS = Op0I->getOperand(0);
4000 Value *Op0RHS = Op0I->getOperand(1);
4001 switch (Op0I->getOpcode()) {
4002 case Instruction::Xor:
4003 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004004 // If the mask is only needed on one incoming arm, push it up.
4005 if (Op0I->hasOneUse()) {
4006 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4007 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004008 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004009 Op0RHS->getName()+".masked");
4010 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004011 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004012 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004013 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004014 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004015 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4016 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004017 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004018 Op0LHS->getName()+".masked");
4019 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004020 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004021 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4022 }
4023 }
4024
Chris Lattner6e7ba452005-01-01 16:22:27 +00004025 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004026 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004027 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4028 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4029 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4030 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004031 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004032 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004033 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004034 break;
4035
4036 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004037 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4038 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4039 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4040 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004041 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004042
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004043 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4044 // has 1's for all bits that the subtraction with A might affect.
4045 if (Op0I->hasOneUse()) {
4046 uint32_t BitWidth = AndRHSMask.getBitWidth();
4047 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4048 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4049
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004050 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004051 if (!(A && A->isZero()) && // avoid infinite recursion.
4052 MaskedValueIsZero(Op0LHS, Mask)) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00004053 Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004054 InsertNewInstBefore(NewNeg, I);
4055 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4056 }
4057 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004058 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004059
4060 case Instruction::Shl:
4061 case Instruction::LShr:
4062 // (1 << x) & 1 --> zext(x == 0)
4063 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004064 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Owen Anderson333c4002009-07-09 23:48:35 +00004065 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4066 Op0RHS, Context->getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004067 InsertNewInstBefore(NewICmp, I);
4068 return new ZExtInst(NewICmp, I.getType());
4069 }
4070 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004071 }
4072
Chris Lattner58403262003-07-23 19:25:52 +00004073 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004074 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004075 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004076 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004077 // If this is an integer truncation or change from signed-to-unsigned, and
4078 // if the source is an and/or with immediate, transform it. This
4079 // frequently occurs for bitfield accesses.
4080 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004081 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004082 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004083 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004084 if (CastOp->getOpcode() == Instruction::And) {
4085 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004086 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4087 // This will fold the two constants together, which may allow
4088 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004089 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004090 CastOp->getOperand(0), I.getType(),
4091 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004092 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004093 // trunc_or_bitcast(C1)&C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004094 Constant *C3 =
4095 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4096 C3 = Context->getConstantExprAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004097 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004098 } else if (CastOp->getOpcode() == Instruction::Or) {
4099 // Change: and (cast (or X, C1) to T), C2
4100 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004101 Constant *C3 =
4102 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4103 if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4104 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004105 return ReplaceInstUsesWith(I, AndRHS);
4106 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004107 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004108 }
Chris Lattner06782f82003-07-23 19:36:21 +00004109 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004110
4111 // Try to fold constant and into select arguments.
4112 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004113 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004114 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004115 if (isa<PHINode>(Op0))
4116 if (Instruction *NV = FoldOpIntoPhi(I))
4117 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004118 }
4119
Owen Andersond672ecb2009-07-03 00:17:18 +00004120 Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4121 Value *Op1NotVal = dyn_castNotVal(Op1, Context);
Chris Lattnera2881962003-02-18 19:28:33 +00004122
Chris Lattner5b62aa72004-06-18 06:07:51 +00004123 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00004124 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004125
Misha Brukmancb6267b2004-07-30 12:50:08 +00004126 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004127 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004128 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004129 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004130 InsertNewInstBefore(Or, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004131 return BinaryOperator::CreateNot(*Context, Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004132 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004133
4134 {
Chris Lattner003b6202007-06-15 05:58:24 +00004135 Value *A = 0, *B = 0, *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004136 if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004137 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4138 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004139
4140 // (A|B) & ~(A&B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004141 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004142 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004143 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004144 }
4145 }
4146
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004147 if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004148 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4149 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004150
4151 // ~(A&B) & (A|B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004152 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004153 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004154 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004155 }
4156 }
Chris Lattner64daab52006-04-01 08:03:55 +00004157
4158 if (Op0->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004159 match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004160 if (A == Op1) { // (A^B)&A -> A&(A^B)
4161 I.swapOperands(); // Simplify below
4162 std::swap(Op0, Op1);
4163 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4164 cast<BinaryOperator>(Op0)->swapOperands();
4165 I.swapOperands(); // Simplify below
4166 std::swap(Op0, Op1);
4167 }
4168 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004169
Chris Lattner64daab52006-04-01 08:03:55 +00004170 if (Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004171 match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004172 if (B == Op0) { // B&(A^B) -> B&(B^A)
4173 cast<BinaryOperator>(Op1)->swapOperands();
4174 std::swap(A, B);
4175 }
4176 if (A == Op0) { // A&(A^B) -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00004177 Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004178 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004179 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004180 }
4181 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004182
4183 // (A&((~A)|B)) -> A&B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004184 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4185 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004186 return BinaryOperator::CreateAnd(A, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004187 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4188 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004189 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004190 }
4191
Reid Spencere4d87aa2006-12-23 06:05:41 +00004192 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4193 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004194 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004195 return R;
4196
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004197 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4198 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4199 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004200 }
4201
Chris Lattner6fc205f2006-05-05 06:39:07 +00004202 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004203 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4204 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4205 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4206 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004207 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004208 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004209 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4210 I.getType(), TD) &&
4211 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4212 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004213 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004214 Op1C->getOperand(0),
4215 I.getName());
4216 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004217 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004218 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004219 }
Chris Lattnere511b742006-11-14 07:46:50 +00004220
4221 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004222 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4223 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4224 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004225 SI0->getOperand(1) == SI1->getOperand(1) &&
4226 (SI0->hasOneUse() || SI1->hasOneUse())) {
4227 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004228 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004229 SI1->getOperand(0),
4230 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004231 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004232 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004233 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004234 }
4235
Evan Cheng8db90722008-10-14 17:15:11 +00004236 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004237 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4238 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4239 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng8db90722008-10-14 17:15:11 +00004240 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4241 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner99c65742007-10-24 05:38:08 +00004242 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4243 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4244 // If either of the constants are nans, then the whole thing returns
4245 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004246 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersond672ecb2009-07-03 00:17:18 +00004247 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00004248 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
4249 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner99c65742007-10-24 05:38:08 +00004250 }
Evan Cheng8db90722008-10-14 17:15:11 +00004251 } else {
4252 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4253 FCmpInst::Predicate Op0CC, Op1CC;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004254 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4255 m_Value(Op0RHS)), *Context) &&
4256 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4257 m_Value(Op1RHS)), *Context)) {
Evan Cheng4990b252008-10-14 18:13:38 +00004258 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4259 // Swap RHS operands to match LHS.
4260 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4261 std::swap(Op1LHS, Op1RHS);
4262 }
Evan Cheng8db90722008-10-14 17:15:11 +00004263 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4264 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4265 if (Op0CC == Op1CC)
Owen Anderson333c4002009-07-09 23:48:35 +00004266 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4267 Op0LHS, Op0RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00004268 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4269 Op1CC == FCmpInst::FCMP_FALSE)
Owen Andersond672ecb2009-07-03 00:17:18 +00004270 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng8db90722008-10-14 17:15:11 +00004271 else if (Op0CC == FCmpInst::FCMP_TRUE)
4272 return ReplaceInstUsesWith(I, Op1);
4273 else if (Op1CC == FCmpInst::FCMP_TRUE)
4274 return ReplaceInstUsesWith(I, Op0);
4275 bool Op0Ordered;
4276 bool Op1Ordered;
4277 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4278 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4279 if (Op1Pred == 0) {
4280 std::swap(Op0, Op1);
4281 std::swap(Op0Pred, Op1Pred);
4282 std::swap(Op0Ordered, Op1Ordered);
4283 }
4284 if (Op0Pred == 0) {
4285 // uno && ueq -> uno && (uno || eq) -> ueq
4286 // ord && olt -> ord && (ord && lt) -> olt
4287 if (Op0Ordered == Op1Ordered)
4288 return ReplaceInstUsesWith(I, Op1);
4289 // uno && oeq -> uno && (ord && eq) -> false
4290 // uno && ord -> false
4291 if (!Op0Ordered)
Owen Andersond672ecb2009-07-03 00:17:18 +00004292 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng8db90722008-10-14 17:15:11 +00004293 // ord && ueq -> ord && (uno || eq) -> oeq
4294 return cast<Instruction>(getFCmpValue(true, Op1Pred,
Owen Andersond672ecb2009-07-03 00:17:18 +00004295 Op0LHS, Op0RHS, Context));
Evan Cheng8db90722008-10-14 17:15:11 +00004296 }
4297 }
4298 }
4299 }
Chris Lattner99c65742007-10-24 05:38:08 +00004300 }
4301 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004302
Chris Lattner7e708292002-06-25 16:13:24 +00004303 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004304}
4305
Chris Lattner8c34cd22008-10-05 02:13:19 +00004306/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4307/// capable of providing pieces of a bswap. The subexpression provides pieces
4308/// of a bswap if it is proven that each of the non-zero bytes in the output of
4309/// the expression came from the corresponding "byte swapped" byte in some other
4310/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4311/// we know that the expression deposits the low byte of %X into the high byte
4312/// of the bswap result and that all other bytes are zero. This expression is
4313/// accepted, the high byte of ByteValues is set to X to indicate a correct
4314/// match.
4315///
4316/// This function returns true if the match was unsuccessful and false if so.
4317/// On entry to the function the "OverallLeftShift" is a signed integer value
4318/// indicating the number of bytes that the subexpression is later shifted. For
4319/// example, if the expression is later right shifted by 16 bits, the
4320/// OverallLeftShift value would be -2 on entry. This is used to specify which
4321/// byte of ByteValues is actually being set.
4322///
4323/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4324/// byte is masked to zero by a user. For example, in (X & 255), X will be
4325/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4326/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4327/// always in the local (OverallLeftShift) coordinate space.
4328///
4329static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4330 SmallVector<Value*, 8> &ByteValues) {
4331 if (Instruction *I = dyn_cast<Instruction>(V)) {
4332 // If this is an or instruction, it may be an inner node of the bswap.
4333 if (I->getOpcode() == Instruction::Or) {
4334 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4335 ByteValues) ||
4336 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4337 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004338 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004339
4340 // If this is a logical shift by a constant multiple of 8, recurse with
4341 // OverallLeftShift and ByteMask adjusted.
4342 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4343 unsigned ShAmt =
4344 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4345 // Ensure the shift amount is defined and of a byte value.
4346 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4347 return true;
4348
4349 unsigned ByteShift = ShAmt >> 3;
4350 if (I->getOpcode() == Instruction::Shl) {
4351 // X << 2 -> collect(X, +2)
4352 OverallLeftShift += ByteShift;
4353 ByteMask >>= ByteShift;
4354 } else {
4355 // X >>u 2 -> collect(X, -2)
4356 OverallLeftShift -= ByteShift;
4357 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004358 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004359 }
4360
4361 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4362 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4363
4364 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4365 ByteValues);
4366 }
4367
4368 // If this is a logical 'and' with a mask that clears bytes, clear the
4369 // corresponding bytes in ByteMask.
4370 if (I->getOpcode() == Instruction::And &&
4371 isa<ConstantInt>(I->getOperand(1))) {
4372 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4373 unsigned NumBytes = ByteValues.size();
4374 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4375 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4376
4377 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4378 // If this byte is masked out by a later operation, we don't care what
4379 // the and mask is.
4380 if ((ByteMask & (1 << i)) == 0)
4381 continue;
4382
4383 // If the AndMask is all zeros for this byte, clear the bit.
4384 APInt MaskB = AndMask & Byte;
4385 if (MaskB == 0) {
4386 ByteMask &= ~(1U << i);
4387 continue;
4388 }
4389
4390 // If the AndMask is not all ones for this byte, it's not a bytezap.
4391 if (MaskB != Byte)
4392 return true;
4393
4394 // Otherwise, this byte is kept.
4395 }
4396
4397 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4398 ByteValues);
4399 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004400 }
4401
Chris Lattner8c34cd22008-10-05 02:13:19 +00004402 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4403 // the input value to the bswap. Some observations: 1) if more than one byte
4404 // is demanded from this input, then it could not be successfully assembled
4405 // into a byteswap. At least one of the two bytes would not be aligned with
4406 // their ultimate destination.
4407 if (!isPowerOf2_32(ByteMask)) return true;
4408 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004409
Chris Lattner8c34cd22008-10-05 02:13:19 +00004410 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4411 // is demanded, it needs to go into byte 0 of the result. This means that the
4412 // byte needs to be shifted until it lands in the right byte bucket. The
4413 // shift amount depends on the position: if the byte is coming from the high
4414 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4415 // low part, it must be shifted left.
4416 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4417 if (InputByteNo < ByteValues.size()/2) {
4418 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4419 return true;
4420 } else {
4421 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4422 return true;
4423 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004424
4425 // If the destination byte value is already defined, the values are or'd
4426 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004427 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004428 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004429 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004430 return false;
4431}
4432
4433/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4434/// If so, insert the new bswap intrinsic and return it.
4435Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004436 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004437 if (!ITy || ITy->getBitWidth() % 16 ||
4438 // ByteMask only allows up to 32-byte values.
4439 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004440 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004441
4442 /// ByteValues - For each byte of the result, we keep track of which value
4443 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004444 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004445 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004446
4447 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004448 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4449 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004450 return 0;
4451
4452 // Check to see if all of the bytes come from the same value.
4453 Value *V = ByteValues[0];
4454 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4455
4456 // Check to make sure that all of the bytes come from the same value.
4457 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4458 if (ByteValues[i] != V)
4459 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004460 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004461 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004462 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004463 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004464}
4465
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004466/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4467/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4468/// we can simplify this expression to "cond ? C : D or B".
4469static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004470 Value *C, Value *D,
4471 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004472 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004473 Value *Cond = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004474 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004475 return 0;
4476
Chris Lattnera6a474d2008-11-16 04:26:55 +00004477 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004478 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004479 return SelectInst::Create(Cond, C, B);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004480 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004481 return SelectInst::Create(Cond, C, B);
4482 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004483 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004484 return SelectInst::Create(Cond, C, D);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004485 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004486 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004487 return 0;
4488}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004489
Chris Lattner69d4ced2008-11-16 05:20:07 +00004490/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4491Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4492 ICmpInst *LHS, ICmpInst *RHS) {
4493 Value *Val, *Val2;
4494 ConstantInt *LHSCst, *RHSCst;
4495 ICmpInst::Predicate LHSCC, RHSCC;
4496
4497 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004498 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4499 m_ConstantInt(LHSCst)), *Context) ||
4500 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4501 m_ConstantInt(RHSCst)), *Context))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004502 return 0;
4503
4504 // From here on, we only handle:
4505 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4506 if (Val != Val2) return 0;
4507
4508 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4509 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4510 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4511 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4512 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4513 return 0;
4514
4515 // We can't fold (ugt x, C) | (sgt x, C2).
4516 if (!PredicatesFoldable(LHSCC, RHSCC))
4517 return 0;
4518
4519 // Ensure that the larger constant is on the RHS.
4520 bool ShouldSwap;
4521 if (ICmpInst::isSignedPredicate(LHSCC) ||
4522 (ICmpInst::isEquality(LHSCC) &&
4523 ICmpInst::isSignedPredicate(RHSCC)))
4524 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4525 else
4526 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4527
4528 if (ShouldSwap) {
4529 std::swap(LHS, RHS);
4530 std::swap(LHSCst, RHSCst);
4531 std::swap(LHSCC, RHSCC);
4532 }
4533
4534 // At this point, we know we have have two icmp instructions
4535 // comparing a value against two constants and or'ing the result
4536 // together. Because of the above check, we know that we only have
4537 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4538 // FoldICmpLogical check above), that the two constants are not
4539 // equal.
4540 assert(LHSCst != RHSCst && "Compares not folded above?");
4541
4542 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004543 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004544 case ICmpInst::ICMP_EQ:
4545 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004546 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004547 case ICmpInst::ICMP_EQ:
Owen Andersond672ecb2009-07-03 00:17:18 +00004548 if (LHSCst == SubOne(RHSCst, Context)) {
4549 // (X == 13 | X == 14) -> X-13 <u 2
4550 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004551 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4552 Val->getName()+".off");
4553 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00004554 AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
Owen Anderson333c4002009-07-09 23:48:35 +00004555 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004556 }
4557 break; // (X == 13 | X == 15) -> no change
4558 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4559 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4560 break;
4561 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4562 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4563 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4564 return ReplaceInstUsesWith(I, RHS);
4565 }
4566 break;
4567 case ICmpInst::ICMP_NE:
4568 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004569 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004570 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4571 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4572 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4573 return ReplaceInstUsesWith(I, LHS);
4574 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4575 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4576 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Andersond672ecb2009-07-03 00:17:18 +00004577 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004578 }
4579 break;
4580 case ICmpInst::ICMP_ULT:
4581 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004582 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004583 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4584 break;
4585 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4586 // If RHSCst is [us]MAXINT, it is always false. Not handling
4587 // this can cause overflow.
4588 if (RHSCst->isMaxValue(false))
4589 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004590 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4591 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004592 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4593 break;
4594 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4595 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4596 return ReplaceInstUsesWith(I, RHS);
4597 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4598 break;
4599 }
4600 break;
4601 case ICmpInst::ICMP_SLT:
4602 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004603 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004604 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4605 break;
4606 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4607 // If RHSCst is [us]MAXINT, it is always false. Not handling
4608 // this can cause overflow.
4609 if (RHSCst->isMaxValue(true))
4610 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004611 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4612 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004613 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4614 break;
4615 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4616 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4617 return ReplaceInstUsesWith(I, RHS);
4618 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4619 break;
4620 }
4621 break;
4622 case ICmpInst::ICMP_UGT:
4623 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004624 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004625 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4626 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4627 return ReplaceInstUsesWith(I, LHS);
4628 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4629 break;
4630 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4631 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Andersond672ecb2009-07-03 00:17:18 +00004632 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004633 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4634 break;
4635 }
4636 break;
4637 case ICmpInst::ICMP_SGT:
4638 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004639 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004640 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4641 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4642 return ReplaceInstUsesWith(I, LHS);
4643 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4644 break;
4645 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4646 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Andersond672ecb2009-07-03 00:17:18 +00004647 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004648 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4649 break;
4650 }
4651 break;
4652 }
4653 return 0;
4654}
4655
Bill Wendlinga698a472008-12-01 08:23:25 +00004656/// FoldOrWithConstants - This helper function folds:
4657///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004658/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004659///
4660/// into:
4661///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004662/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004663///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004664/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004665Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004666 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004667 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4668 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004669
Bill Wendling286a0542008-12-02 06:24:20 +00004670 Value *V1 = 0;
4671 ConstantInt *CI2 = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004672 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004673
Bill Wendling29976b92008-12-02 06:18:11 +00004674 APInt Xor = CI1->getValue() ^ CI2->getValue();
4675 if (!Xor.isAllOnesValue()) return 0;
4676
Bill Wendling286a0542008-12-02 06:24:20 +00004677 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004678 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004679 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4680 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004681 }
4682
4683 return 0;
4684}
4685
Chris Lattner7e708292002-06-25 16:13:24 +00004686Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004687 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004688 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004689
Chris Lattner42593e62007-03-24 23:56:43 +00004690 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004691 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004692
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004693 // or X, X = X
4694 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004695 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004696
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004697 // See if we can simplify any instructions used by the instruction whose sole
4698 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004699 if (SimplifyDemandedInstructionBits(I))
4700 return &I;
4701 if (isa<VectorType>(I.getType())) {
4702 if (isa<ConstantAggregateZero>(Op1)) {
4703 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4704 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4705 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4706 return ReplaceInstUsesWith(I, I.getOperand(1));
4707 }
Chris Lattner42593e62007-03-24 23:56:43 +00004708 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004709
Chris Lattner3f5b8772002-05-06 16:14:14 +00004710 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004711 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004712 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004713 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004714 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) &&
4715 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004716 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004717 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004718 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004719 return BinaryOperator::CreateAnd(Or,
Owen Andersond672ecb2009-07-03 00:17:18 +00004720 Context->getConstantInt(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004721 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004722
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004723 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004724 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) &&
4725 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004726 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004727 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004728 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004729 return BinaryOperator::CreateXor(Or,
Owen Andersond672ecb2009-07-03 00:17:18 +00004730 Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004731 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004732
4733 // Try to fold constant and into select arguments.
4734 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004735 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004736 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004737 if (isa<PHINode>(Op0))
4738 if (Instruction *NV = FoldOpIntoPhi(I))
4739 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004740 }
4741
Chris Lattner4f637d42006-01-06 17:59:59 +00004742 Value *A = 0, *B = 0;
4743 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004744
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004745 if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004746 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4747 return ReplaceInstUsesWith(I, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004748 if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004749 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4750 return ReplaceInstUsesWith(I, Op0);
4751
Chris Lattner6423d4c2006-07-10 20:25:24 +00004752 // (A | B) | C and A | (B | C) -> bswap if possible.
4753 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004754 if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4755 match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4756 (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4757 match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004758 if (Instruction *BSwap = MatchBSwap(I))
4759 return BSwap;
4760 }
4761
Chris Lattner6e4c6492005-05-09 04:58:36 +00004762 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004763 if (Op0->hasOneUse() &&
4764 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004765 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004766 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004767 InsertNewInstBefore(NOr, I);
4768 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004769 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004770 }
4771
4772 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004773 if (Op1->hasOneUse() &&
4774 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004775 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004776 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004777 InsertNewInstBefore(NOr, I);
4778 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004779 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004780 }
4781
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004782 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004783 Value *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004784 if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4785 match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004786 Value *V1 = 0, *V2 = 0, *V3 = 0;
4787 C1 = dyn_cast<ConstantInt>(C);
4788 C2 = dyn_cast<ConstantInt>(D);
4789 if (C1 && C2) { // (A & C1)|(B & C2)
4790 // If we have: ((V + N) & C1) | (V & C2)
4791 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4792 // replace with V+N.
4793 if (C1->getValue() == ~C2->getValue()) {
4794 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004795 match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004796 // Add commutes, try both ways.
4797 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4798 return ReplaceInstUsesWith(I, A);
4799 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4800 return ReplaceInstUsesWith(I, A);
4801 }
4802 // Or commutes, try both ways.
4803 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004804 match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004805 // Add commutes, try both ways.
4806 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4807 return ReplaceInstUsesWith(I, B);
4808 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4809 return ReplaceInstUsesWith(I, B);
4810 }
4811 }
Chris Lattner044e5332007-04-08 08:01:49 +00004812 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004813 }
4814
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004815 // Check to see if we have any common things being and'ed. If so, find the
4816 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004817 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4818 if (A == B) // (A & C)|(A & D) == A & (C|D)
4819 V1 = A, V2 = C, V3 = D;
4820 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4821 V1 = A, V2 = B, V3 = C;
4822 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4823 V1 = C, V2 = A, V3 = D;
4824 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4825 V1 = C, V2 = A, V3 = B;
4826
4827 if (V1) {
4828 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004829 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4830 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004831 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004832 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004833
Dan Gohman1975d032008-10-30 20:40:10 +00004834 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004835 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004836 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004837 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004838 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004839 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004840 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004841 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004842 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004843
Bill Wendlingb01865c2008-11-30 13:52:49 +00004844 // ((A&~B)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004845 if ((match(C, m_Not(m_Specific(D)), *Context) &&
4846 match(B, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004847 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004848 // ((~B&A)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004849 if ((match(A, m_Not(m_Specific(D)), *Context) &&
4850 match(B, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004851 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004852 // ((A&~B)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004853 if ((match(C, m_Not(m_Specific(B)), *Context) &&
4854 match(D, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004855 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004856 // ((~B&A)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004857 if ((match(A, m_Not(m_Specific(B)), *Context) &&
4858 match(D, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004859 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004860 }
Chris Lattnere511b742006-11-14 07:46:50 +00004861
4862 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004863 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4864 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4865 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004866 SI0->getOperand(1) == SI1->getOperand(1) &&
4867 (SI0->hasOneUse() || SI1->hasOneUse())) {
4868 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004869 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004870 SI1->getOperand(0),
4871 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004872 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004873 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004874 }
4875 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004876
Bill Wendlingb3833d12008-12-01 01:07:11 +00004877 // ((A|B)&1)|(B&-2) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004878 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4879 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004880 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004881 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004882 }
4883 // (B&-2)|((A|B)&1) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004884 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4885 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004886 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004887 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004888 }
4889
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004890 if (match(Op0, m_Not(m_Value(A)), *Context)) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004891 if (A == Op1) // ~A | A == -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004892 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004893 } else {
4894 A = 0;
4895 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004896 // Note, A is still live here!
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004897 if (match(Op1, m_Not(m_Value(B)), *Context)) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004898 if (Op0 == B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004899 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004900
Misha Brukmancb6267b2004-07-30 12:50:08 +00004901 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004902 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004903 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004904 I.getName()+".demorgan"), I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004905 return BinaryOperator::CreateNot(*Context, And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004906 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004907 }
Chris Lattnera2881962003-02-18 19:28:33 +00004908
Reid Spencere4d87aa2006-12-23 06:05:41 +00004909 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4910 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004911 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004912 return R;
4913
Chris Lattner69d4ced2008-11-16 05:20:07 +00004914 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4915 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4916 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004917 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004918
4919 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004920 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004921 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004922 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004923 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4924 !isa<ICmpInst>(Op1C->getOperand(0))) {
4925 const Type *SrcTy = Op0C->getOperand(0)->getType();
4926 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4927 // Only do this if the casts both really cause code to be
4928 // generated.
4929 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4930 I.getType(), TD) &&
4931 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4932 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004933 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004934 Op1C->getOperand(0),
4935 I.getName());
4936 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004937 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004938 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004939 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004940 }
Chris Lattner99c65742007-10-24 05:38:08 +00004941 }
4942
4943
4944 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4945 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4946 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4947 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004948 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004949 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004950 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4951 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4952 // If either of the constants are nans, then the whole thing returns
4953 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004954 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersond672ecb2009-07-03 00:17:18 +00004955 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner99c65742007-10-24 05:38:08 +00004956
4957 // Otherwise, no need to compare the two constants, compare the
4958 // rest.
Owen Anderson333c4002009-07-09 23:48:35 +00004959 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4960 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner99c65742007-10-24 05:38:08 +00004961 }
Evan Cheng40300622008-10-14 18:44:08 +00004962 } else {
4963 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4964 FCmpInst::Predicate Op0CC, Op1CC;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004965 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4966 m_Value(Op0RHS)), *Context) &&
4967 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4968 m_Value(Op1RHS)), *Context)) {
Evan Cheng40300622008-10-14 18:44:08 +00004969 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4970 // Swap RHS operands to match LHS.
4971 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4972 std::swap(Op1LHS, Op1RHS);
4973 }
4974 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4975 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4976 if (Op0CC == Op1CC)
Owen Anderson333c4002009-07-09 23:48:35 +00004977 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4978 Op0LHS, Op0RHS);
Evan Cheng40300622008-10-14 18:44:08 +00004979 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4980 Op1CC == FCmpInst::FCMP_TRUE)
Owen Andersond672ecb2009-07-03 00:17:18 +00004981 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng40300622008-10-14 18:44:08 +00004982 else if (Op0CC == FCmpInst::FCMP_FALSE)
4983 return ReplaceInstUsesWith(I, Op1);
4984 else if (Op1CC == FCmpInst::FCMP_FALSE)
4985 return ReplaceInstUsesWith(I, Op0);
4986 bool Op0Ordered;
4987 bool Op1Ordered;
4988 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4989 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4990 if (Op0Ordered == Op1Ordered) {
4991 // If both are ordered or unordered, return a new fcmp with
4992 // or'ed predicates.
4993 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
Owen Andersond672ecb2009-07-03 00:17:18 +00004994 Op0LHS, Op0RHS, Context);
Evan Cheng40300622008-10-14 18:44:08 +00004995 if (Instruction *I = dyn_cast<Instruction>(RV))
4996 return I;
4997 // Otherwise, it's a constant boolean value...
4998 return ReplaceInstUsesWith(I, RV);
4999 }
5000 }
5001 }
5002 }
Chris Lattner99c65742007-10-24 05:38:08 +00005003 }
5004 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005005
Chris Lattner7e708292002-06-25 16:13:24 +00005006 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005007}
5008
Dan Gohman844731a2008-05-13 00:00:25 +00005009namespace {
5010
Chris Lattnerc317d392004-02-16 01:20:27 +00005011// XorSelf - Implements: X ^ X --> 0
5012struct XorSelf {
5013 Value *RHS;
5014 XorSelf(Value *rhs) : RHS(rhs) {}
5015 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5016 Instruction *apply(BinaryOperator &Xor) const {
5017 return &Xor;
5018 }
5019};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005020
Dan Gohman844731a2008-05-13 00:00:25 +00005021}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005022
Chris Lattner7e708292002-06-25 16:13:24 +00005023Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005024 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005025 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005026
Evan Chengd34af782008-03-25 20:07:13 +00005027 if (isa<UndefValue>(Op1)) {
5028 if (isa<UndefValue>(Op0))
5029 // Handle undef ^ undef -> 0 special case. This is a common
5030 // idiom (misuse).
Owen Andersond672ecb2009-07-03 00:17:18 +00005031 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005032 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005033 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005034
Chris Lattnerc317d392004-02-16 01:20:27 +00005035 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Owen Andersond672ecb2009-07-03 00:17:18 +00005036 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005037 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersond672ecb2009-07-03 00:17:18 +00005038 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005039 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005040
5041 // See if we can simplify any instructions used by the instruction whose sole
5042 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005043 if (SimplifyDemandedInstructionBits(I))
5044 return &I;
5045 if (isa<VectorType>(I.getType()))
5046 if (isa<ConstantAggregateZero>(Op1))
5047 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005048
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005049 // Is this a ~ operation?
Owen Andersond672ecb2009-07-03 00:17:18 +00005050 if (Value *NotOp = dyn_castNotVal(&I, Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005051 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5052 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5053 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5054 if (Op0I->getOpcode() == Instruction::And ||
5055 Op0I->getOpcode() == Instruction::Or) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005056 if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5057 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005058 Instruction *NotY =
Owen Anderson73c6b712009-07-13 20:58:05 +00005059 BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005060 Op0I->getOperand(1)->getName()+".not");
5061 InsertNewInstBefore(NotY, I);
5062 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005063 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005064 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005065 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005066 }
5067 }
5068 }
5069 }
5070
5071
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005072 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005073 if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005074 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005075 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005076 return new ICmpInst(*Context, ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005077 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005078
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005079 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005080 return new FCmpInst(*Context, FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005081 FCI->getOperand(0), FCI->getOperand(1));
5082 }
5083
Nick Lewycky517e1f52008-05-31 19:01:33 +00005084 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5085 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5086 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5087 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5088 Instruction::CastOps Opcode = Op0C->getOpcode();
5089 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005090 if (RHS == Context->getConstantExprCast(Opcode,
5091 Context->getConstantIntTrue(),
Nick Lewycky517e1f52008-05-31 19:01:33 +00005092 Op0C->getDestTy())) {
5093 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
Owen Anderson333c4002009-07-09 23:48:35 +00005094 *Context,
Nick Lewycky517e1f52008-05-31 19:01:33 +00005095 CI->getOpcode(), CI->getInversePredicate(),
5096 CI->getOperand(0), CI->getOperand(1)), I);
5097 NewCI->takeName(CI);
5098 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5099 }
5100 }
5101 }
5102 }
5103 }
5104
Reid Spencere4d87aa2006-12-23 06:05:41 +00005105 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005106 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005107 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5108 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005109 Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5110 Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5111 Context->getConstantInt(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005112 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005113 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005114
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005115 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005116 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005117 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005118 if (RHS->isAllOnesValue()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005119 Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005120 return BinaryOperator::CreateSub(
Owen Andersond672ecb2009-07-03 00:17:18 +00005121 Context->getConstantExprSub(NegOp0CI,
5122 Context->getConstantInt(I.getType(), 1)),
5123 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005124 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005125 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersond672ecb2009-07-03 00:17:18 +00005126 Constant *C =
5127 Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005128 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005129
Chris Lattner7c4049c2004-01-12 19:35:11 +00005130 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005131 } else if (Op0I->getOpcode() == Instruction::Or) {
5132 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005133 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005134 Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005135 // Anything in both C1 and C2 is known to be zero, remove it from
5136 // NewRHS.
Owen Andersond672ecb2009-07-03 00:17:18 +00005137 Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5138 NewRHS = Context->getConstantExprAnd(NewRHS,
5139 Context->getConstantExprNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005140 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005141 I.setOperand(0, Op0I->getOperand(0));
5142 I.setOperand(1, NewRHS);
5143 return &I;
5144 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005145 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005146 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005147 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005148
5149 // Try to fold constant and into select arguments.
5150 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005151 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005152 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005153 if (isa<PHINode>(Op0))
5154 if (Instruction *NV = FoldOpIntoPhi(I))
5155 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005156 }
5157
Owen Andersond672ecb2009-07-03 00:17:18 +00005158 if (Value *X = dyn_castNotVal(Op0, Context)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005159 if (X == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005160 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005161
Owen Andersond672ecb2009-07-03 00:17:18 +00005162 if (Value *X = dyn_castNotVal(Op1, Context)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005163 if (X == Op0)
Owen Andersond672ecb2009-07-03 00:17:18 +00005164 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005165
Chris Lattner318bf792007-03-18 22:51:34 +00005166
5167 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5168 if (Op1I) {
5169 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005170 if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005171 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005172 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005173 I.swapOperands();
5174 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005175 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005176 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005177 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005178 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005179 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005180 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005181 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005182 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005183 } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) &&
5184 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005185 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005186 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005187 std::swap(A, B);
5188 }
Chris Lattner318bf792007-03-18 22:51:34 +00005189 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005190 I.swapOperands(); // Simplified below.
5191 std::swap(Op0, Op1);
5192 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005193 }
Chris Lattner318bf792007-03-18 22:51:34 +00005194 }
5195
5196 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5197 if (Op0I) {
5198 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005199 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5200 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005201 if (A == Op1) // (B|A)^B == (A|B)^B
5202 std::swap(A, B);
5203 if (B == Op1) { // (A|B)^B == A & ~B
5204 Instruction *NotB =
Owen Anderson73c6b712009-07-13 20:58:05 +00005205 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
5206 Op1, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005207 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005208 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005209 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005210 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005211 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005212 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005213 } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5214 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005215 if (A == Op1) // (A&B)^A -> (B&A)^A
5216 std::swap(A, B);
5217 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005218 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005219 Instruction *N =
Owen Anderson73c6b712009-07-13 20:58:05 +00005220 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005221 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005222 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005223 }
Chris Lattner318bf792007-03-18 22:51:34 +00005224 }
5225
5226 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5227 if (Op0I && Op1I && Op0I->isShift() &&
5228 Op0I->getOpcode() == Op1I->getOpcode() &&
5229 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5230 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5231 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005232 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005233 Op1I->getOperand(0),
5234 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005235 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005236 Op1I->getOperand(1));
5237 }
5238
5239 if (Op0I && Op1I) {
5240 Value *A, *B, *C, *D;
5241 // (A & B)^(A | B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005242 if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5243 match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005244 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005245 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005246 }
5247 // (A | B)^(A & B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005248 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5249 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005250 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005251 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005252 }
5253
5254 // (A & B)^(C & D)
5255 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005256 match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5257 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005258 // (X & Y)^(X & Y) -> (Y^Z) & X
5259 Value *X = 0, *Y = 0, *Z = 0;
5260 if (A == C)
5261 X = A, Y = B, Z = D;
5262 else if (A == D)
5263 X = A, Y = B, Z = C;
5264 else if (B == C)
5265 X = B, Y = A, Z = D;
5266 else if (B == D)
5267 X = B, Y = A, Z = C;
5268
5269 if (X) {
5270 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005271 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5272 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005273 }
5274 }
5275 }
5276
Reid Spencere4d87aa2006-12-23 06:05:41 +00005277 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5278 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005279 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005280 return R;
5281
Chris Lattner6fc205f2006-05-05 06:39:07 +00005282 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005283 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005284 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005285 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5286 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005287 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005288 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005289 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5290 I.getType(), TD) &&
5291 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5292 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005293 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005294 Op1C->getOperand(0),
5295 I.getName());
5296 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005297 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005298 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005299 }
Chris Lattner99c65742007-10-24 05:38:08 +00005300 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005301
Chris Lattner7e708292002-06-25 16:13:24 +00005302 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005303}
5304
Owen Andersond672ecb2009-07-03 00:17:18 +00005305static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005306 LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005307 return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005308}
Chris Lattnera96879a2004-09-29 17:40:11 +00005309
Dan Gohman6de29f82009-06-15 22:12:54 +00005310static bool HasAddOverflow(ConstantInt *Result,
5311 ConstantInt *In1, ConstantInt *In2,
5312 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005313 if (IsSigned)
5314 if (In2->getValue().isNegative())
5315 return Result->getValue().sgt(In1->getValue());
5316 else
5317 return Result->getValue().slt(In1->getValue());
5318 else
5319 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005320}
5321
Dan Gohman6de29f82009-06-15 22:12:54 +00005322/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005323/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005324static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005325 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005326 bool IsSigned = false) {
5327 Result = Context->getConstantExprAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005328
Dan Gohman6de29f82009-06-15 22:12:54 +00005329 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5330 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005331 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5332 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5333 ExtractElement(In1, Idx, Context),
5334 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005335 IsSigned))
5336 return true;
5337 }
5338 return false;
5339 }
5340
5341 return HasAddOverflow(cast<ConstantInt>(Result),
5342 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5343 IsSigned);
5344}
5345
5346static bool HasSubOverflow(ConstantInt *Result,
5347 ConstantInt *In1, ConstantInt *In2,
5348 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005349 if (IsSigned)
5350 if (In2->getValue().isNegative())
5351 return Result->getValue().slt(In1->getValue());
5352 else
5353 return Result->getValue().sgt(In1->getValue());
5354 else
5355 return Result->getValue().ugt(In1->getValue());
5356}
5357
Dan Gohman6de29f82009-06-15 22:12:54 +00005358/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5359/// overflowed for this type.
5360static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005361 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005362 bool IsSigned = false) {
5363 Result = Context->getConstantExprSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005364
5365 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5366 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005367 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5368 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5369 ExtractElement(In1, Idx, Context),
5370 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005371 IsSigned))
5372 return true;
5373 }
5374 return false;
5375 }
5376
5377 return HasSubOverflow(cast<ConstantInt>(Result),
5378 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5379 IsSigned);
5380}
5381
Chris Lattner574da9b2005-01-13 20:14:25 +00005382/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5383/// code necessary to compute the offset from the base pointer (without adding
5384/// in the base pointer). Return the result as a signed integer of intptr size.
5385static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5386 TargetData &TD = IC.getTargetData();
5387 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005388 const Type *IntPtrTy = TD.getIntPtrType();
Owen Anderson07cf79e2009-07-06 23:00:19 +00005389 LLVMContext *Context = IC.getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00005390 Value *Result = Context->getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005391
5392 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005393 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005394 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005395
Gabor Greif177dd3f2008-06-12 21:37:33 +00005396 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5397 ++i, ++GTI) {
5398 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005399 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005400 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5401 if (OpC->isZero()) continue;
5402
5403 // Handle a struct index, which adds its field offset to the pointer.
5404 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5405 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5406
5407 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005408 Result =
5409 Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005410 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005411 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005412 BinaryOperator::CreateAdd(Result,
Owen Andersond672ecb2009-07-03 00:17:18 +00005413 Context->getConstantInt(IntPtrTy, Size),
Chris Lattnere62f0212007-04-28 04:52:43 +00005414 GEP->getName()+".offs"), I);
5415 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005416 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005417
Owen Andersond672ecb2009-07-03 00:17:18 +00005418 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5419 Constant *OC =
5420 Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5421 Scale = Context->getConstantExprMul(OC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005422 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005423 Result = Context->getConstantExprAdd(RC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005424 else {
5425 // Emit an add instruction.
5426 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005427 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005428 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005429 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005430 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005431 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005432 // Convert to correct type.
5433 if (Op->getType() != IntPtrTy) {
5434 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005435 Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005436 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005437 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5438 true,
5439 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005440 }
5441 if (Size != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005442 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
Chris Lattnere62f0212007-04-28 04:52:43 +00005443 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005444 Op = Context->getConstantExprMul(OpC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005445 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005446 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005447 GEP->getName()+".idx"), I);
5448 }
5449
5450 // Emit an add instruction.
5451 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005452 Result = Context->getConstantExprAdd(cast<Constant>(Op),
Chris Lattnere62f0212007-04-28 04:52:43 +00005453 cast<Constant>(Result));
5454 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005455 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005456 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005457 }
5458 return Result;
5459}
5460
Chris Lattner10c0d912008-04-22 02:53:33 +00005461
Dan Gohman8f080f02009-07-17 22:16:21 +00005462/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5463/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5464/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5465/// be complex, and scales are involved. The above expression would also be
5466/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5467/// This later form is less amenable to optimization though, and we are allowed
5468/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005469///
5470/// If we can't emit an optimized form for this expression, this returns null.
5471///
5472static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5473 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005474 TargetData &TD = IC.getTargetData();
5475 gep_type_iterator GTI = gep_type_begin(GEP);
5476
5477 // Check to see if this gep only has a single variable index. If so, and if
5478 // any constant indices are a multiple of its scale, then we can compute this
5479 // in terms of the scale of the variable index. For example, if the GEP
5480 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5481 // because the expression will cross zero at the same point.
5482 unsigned i, e = GEP->getNumOperands();
5483 int64_t Offset = 0;
5484 for (i = 1; i != e; ++i, ++GTI) {
5485 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5486 // Compute the aggregate offset of constant indices.
5487 if (CI->isZero()) continue;
5488
5489 // Handle a struct index, which adds its field offset to the pointer.
5490 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5491 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5492 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005493 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005494 Offset += Size*CI->getSExtValue();
5495 }
5496 } else {
5497 // Found our variable index.
5498 break;
5499 }
5500 }
5501
5502 // If there are no variable indices, we must have a constant offset, just
5503 // evaluate it the general way.
5504 if (i == e) return 0;
5505
5506 Value *VariableIdx = GEP->getOperand(i);
5507 // Determine the scale factor of the variable element. For example, this is
5508 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005509 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005510
5511 // Verify that there are no other variable indices. If so, emit the hard way.
5512 for (++i, ++GTI; i != e; ++i, ++GTI) {
5513 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5514 if (!CI) return 0;
5515
5516 // Compute the aggregate offset of constant indices.
5517 if (CI->isZero()) continue;
5518
5519 // Handle a struct index, which adds its field offset to the pointer.
5520 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5521 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5522 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005523 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005524 Offset += Size*CI->getSExtValue();
5525 }
5526 }
5527
5528 // Okay, we know we have a single variable index, which must be a
5529 // pointer/array/vector index. If there is no offset, life is simple, return
5530 // the index.
5531 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5532 if (Offset == 0) {
5533 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5534 // we don't need to bother extending: the extension won't affect where the
5535 // computation crosses zero.
5536 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5537 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5538 VariableIdx->getNameStart(), &I);
5539 return VariableIdx;
5540 }
5541
5542 // Otherwise, there is an index. The computation we will do will be modulo
5543 // the pointer size, so get it.
5544 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5545
5546 Offset &= PtrSizeMask;
5547 VariableScale &= PtrSizeMask;
5548
5549 // To do this transformation, any constant index must be a multiple of the
5550 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5551 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5552 // multiple of the variable scale.
5553 int64_t NewOffs = Offset / (int64_t)VariableScale;
5554 if (Offset != NewOffs*(int64_t)VariableScale)
5555 return 0;
5556
5557 // Okay, we can do this evaluation. Start by converting the index to intptr.
5558 const Type *IntPtrTy = TD.getIntPtrType();
5559 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005560 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005561 true /*SExt*/,
5562 VariableIdx->getNameStart(), &I);
Owen Andersond672ecb2009-07-03 00:17:18 +00005563 Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005564 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005565}
5566
5567
Reid Spencere4d87aa2006-12-23 06:05:41 +00005568/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005569/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005570Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5571 ICmpInst::Predicate Cond,
5572 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005573 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005574
Chris Lattner10c0d912008-04-22 02:53:33 +00005575 // Look through bitcasts.
5576 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5577 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005578
Chris Lattner574da9b2005-01-13 20:14:25 +00005579 Value *PtrBase = GEPLHS->getOperand(0);
5580 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005581 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005582 // This transformation (ignoring the base and scales) is valid because we
5583 // know pointers can't overflow. See if we can output an optimized form.
5584 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5585
5586 // If not, synthesize the offset the hard way.
5587 if (Offset == 0)
5588 Offset = EmitGEPOffset(GEPLHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005589 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersond672ecb2009-07-03 00:17:18 +00005590 Context->getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005591 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005592 // If the base pointers are different, but the indices are the same, just
5593 // compare the base pointer.
5594 if (PtrBase != GEPRHS->getOperand(0)) {
5595 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005596 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005597 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005598 if (IndicesTheSame)
5599 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5600 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5601 IndicesTheSame = false;
5602 break;
5603 }
5604
5605 // If all indices are the same, just compare the base pointers.
5606 if (IndicesTheSame)
Owen Anderson333c4002009-07-09 23:48:35 +00005607 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005608 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005609
5610 // Otherwise, the base pointers are different and the indices are
5611 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005612 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005613 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005614
Chris Lattnere9d782b2005-01-13 22:25:21 +00005615 // If one of the GEPs has all zero indices, recurse.
5616 bool AllZeros = true;
5617 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5618 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5619 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5620 AllZeros = false;
5621 break;
5622 }
5623 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005624 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5625 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005626
5627 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005628 AllZeros = true;
5629 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5630 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5631 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5632 AllZeros = false;
5633 break;
5634 }
5635 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005636 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005637
Chris Lattner4401c9c2005-01-14 00:20:05 +00005638 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5639 // If the GEPs only differ by one index, compare it.
5640 unsigned NumDifferences = 0; // Keep track of # differences.
5641 unsigned DiffOperand = 0; // The operand that differs.
5642 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5643 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005644 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5645 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005646 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005647 NumDifferences = 2;
5648 break;
5649 } else {
5650 if (NumDifferences++) break;
5651 DiffOperand = i;
5652 }
5653 }
5654
5655 if (NumDifferences == 0) // SAME GEP?
5656 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Andersond672ecb2009-07-03 00:17:18 +00005657 Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005658 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005659
Chris Lattner4401c9c2005-01-14 00:20:05 +00005660 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005661 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5662 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005663 // Make sure we do a signed comparison here.
Owen Anderson333c4002009-07-09 23:48:35 +00005664 return new ICmpInst(*Context,
5665 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005666 }
5667 }
5668
Reid Spencere4d87aa2006-12-23 06:05:41 +00005669 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005670 // the result to fold to a constant!
5671 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5672 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5673 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5674 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5675 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005676 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005677 }
5678 }
5679 return 0;
5680}
5681
Chris Lattnera5406232008-05-19 20:18:56 +00005682/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5683///
5684Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5685 Instruction *LHSI,
5686 Constant *RHSC) {
5687 if (!isa<ConstantFP>(RHSC)) return 0;
5688 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5689
5690 // Get the width of the mantissa. We don't want to hack on conversions that
5691 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005692 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005693 if (MantissaWidth == -1) return 0; // Unknown.
5694
5695 // Check to see that the input is converted from an integer type that is small
5696 // enough that preserves all bits. TODO: check here for "known" sign bits.
5697 // 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 +00005698 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005699
5700 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005701 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5702 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005703 ++InputSize;
5704
5705 // If the conversion would lose info, don't hack on this.
5706 if ((int)InputSize > MantissaWidth)
5707 return 0;
5708
5709 // Otherwise, we can potentially simplify the comparison. We know that it
5710 // will always come through as an integer value and we know the constant is
5711 // not a NAN (it would have been previously simplified).
5712 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5713
5714 ICmpInst::Predicate Pred;
5715 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005716 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005717 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005718 case FCmpInst::FCMP_OEQ:
5719 Pred = ICmpInst::ICMP_EQ;
5720 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005721 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005722 case FCmpInst::FCMP_OGT:
5723 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5724 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005725 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005726 case FCmpInst::FCMP_OGE:
5727 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5728 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005729 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005730 case FCmpInst::FCMP_OLT:
5731 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5732 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005733 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005734 case FCmpInst::FCMP_OLE:
5735 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5736 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005737 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005738 case FCmpInst::FCMP_ONE:
5739 Pred = ICmpInst::ICMP_NE;
5740 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005741 case FCmpInst::FCMP_ORD:
Owen Andersond672ecb2009-07-03 00:17:18 +00005742 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005743 case FCmpInst::FCMP_UNO:
Owen Andersond672ecb2009-07-03 00:17:18 +00005744 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005745 }
5746
5747 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5748
5749 // Now we know that the APFloat is a normal number, zero or inf.
5750
Chris Lattner85162782008-05-20 03:50:52 +00005751 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005752 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005753 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005754
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005755 if (!LHSUnsigned) {
5756 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5757 // and large values.
5758 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5759 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5760 APFloat::rmNearestTiesToEven);
5761 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5762 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5763 Pred == ICmpInst::ICMP_SLE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005764 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5765 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005766 }
5767 } else {
5768 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5769 // +INF and large values.
5770 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5771 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5772 APFloat::rmNearestTiesToEven);
5773 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5774 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5775 Pred == ICmpInst::ICMP_ULE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005776 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5777 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005778 }
Chris Lattnera5406232008-05-19 20:18:56 +00005779 }
5780
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005781 if (!LHSUnsigned) {
5782 // See if the RHS value is < SignedMin.
5783 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5784 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5785 APFloat::rmNearestTiesToEven);
5786 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5787 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5788 Pred == ICmpInst::ICMP_SGE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005789 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5790 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005791 }
Chris Lattnera5406232008-05-19 20:18:56 +00005792 }
5793
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005794 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5795 // [0, UMAX], but it may still be fractional. See if it is fractional by
5796 // casting the FP value to the integer value and back, checking for equality.
5797 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005798 Constant *RHSInt = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005799 ? Context->getConstantExprFPToUI(RHSC, IntTy)
5800 : Context->getConstantExprFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005801 if (!RHS.isZero()) {
5802 bool Equal = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005803 ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5804 : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005805 if (!Equal) {
5806 // If we had a comparison against a fractional value, we have to adjust
5807 // the compare predicate and sometimes the value. RHSC is rounded towards
5808 // zero at this point.
5809 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005810 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005811 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Andersond672ecb2009-07-03 00:17:18 +00005812 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005813 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Andersond672ecb2009-07-03 00:17:18 +00005814 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005815 case ICmpInst::ICMP_ULE:
5816 // (float)int <= 4.4 --> int <= 4
5817 // (float)int <= -4.4 --> false
5818 if (RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005819 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005820 break;
5821 case ICmpInst::ICMP_SLE:
5822 // (float)int <= 4.4 --> int <= 4
5823 // (float)int <= -4.4 --> int < -4
5824 if (RHS.isNegative())
5825 Pred = ICmpInst::ICMP_SLT;
5826 break;
5827 case ICmpInst::ICMP_ULT:
5828 // (float)int < -4.4 --> false
5829 // (float)int < 4.4 --> int <= 4
5830 if (RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005831 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005832 Pred = ICmpInst::ICMP_ULE;
5833 break;
5834 case ICmpInst::ICMP_SLT:
5835 // (float)int < -4.4 --> int < -4
5836 // (float)int < 4.4 --> int <= 4
5837 if (!RHS.isNegative())
5838 Pred = ICmpInst::ICMP_SLE;
5839 break;
5840 case ICmpInst::ICMP_UGT:
5841 // (float)int > 4.4 --> int > 4
5842 // (float)int > -4.4 --> true
5843 if (RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005844 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005845 break;
5846 case ICmpInst::ICMP_SGT:
5847 // (float)int > 4.4 --> int > 4
5848 // (float)int > -4.4 --> int >= -4
5849 if (RHS.isNegative())
5850 Pred = ICmpInst::ICMP_SGE;
5851 break;
5852 case ICmpInst::ICMP_UGE:
5853 // (float)int >= -4.4 --> true
5854 // (float)int >= 4.4 --> int > 4
5855 if (!RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005856 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005857 Pred = ICmpInst::ICMP_UGT;
5858 break;
5859 case ICmpInst::ICMP_SGE:
5860 // (float)int >= -4.4 --> int >= -4
5861 // (float)int >= 4.4 --> int > 4
5862 if (!RHS.isNegative())
5863 Pred = ICmpInst::ICMP_SGT;
5864 break;
5865 }
Chris Lattnera5406232008-05-19 20:18:56 +00005866 }
5867 }
5868
5869 // Lower this FP comparison into an appropriate integer version of the
5870 // comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00005871 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005872}
5873
Reid Spencere4d87aa2006-12-23 06:05:41 +00005874Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5875 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005876 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005877
Chris Lattner58e97462007-01-14 19:42:17 +00005878 // Fold trivial predicates.
5879 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005880 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005881 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005882 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005883
5884 // Simplify 'fcmp pred X, X'
5885 if (Op0 == Op1) {
5886 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005887 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005888 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5889 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5890 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Andersond672ecb2009-07-03 00:17:18 +00005891 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005892 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5893 case FCmpInst::FCMP_OLT: // True if ordered and less than
5894 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Andersond672ecb2009-07-03 00:17:18 +00005895 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005896
5897 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5898 case FCmpInst::FCMP_ULT: // True if unordered or less than
5899 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5900 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5901 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5902 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersond672ecb2009-07-03 00:17:18 +00005903 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005904 return &I;
5905
5906 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5907 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5908 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5909 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5910 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5911 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersond672ecb2009-07-03 00:17:18 +00005912 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005913 return &I;
5914 }
5915 }
5916
Reid Spencere4d87aa2006-12-23 06:05:41 +00005917 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005918 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005919
Reid Spencere4d87aa2006-12-23 06:05:41 +00005920 // Handle fcmp with constant RHS
5921 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005922 // If the constant is a nan, see if we can fold the comparison based on it.
5923 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5924 if (CFP->getValueAPF().isNaN()) {
5925 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Andersond672ecb2009-07-03 00:17:18 +00005926 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005927 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5928 "Comparison must be either ordered or unordered!");
5929 // True if unordered.
Owen Andersond672ecb2009-07-03 00:17:18 +00005930 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005931 }
5932 }
5933
Reid Spencere4d87aa2006-12-23 06:05:41 +00005934 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5935 switch (LHSI->getOpcode()) {
5936 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005937 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5938 // block. If in the same block, we're encouraging jump threading. If
5939 // not, we are just pessimizing the code by making an i1 phi.
5940 if (LHSI->getParent() == I.getParent())
5941 if (Instruction *NV = FoldOpIntoPhi(I))
5942 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005943 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005944 case Instruction::SIToFP:
5945 case Instruction::UIToFP:
5946 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5947 return NV;
5948 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005949 case Instruction::Select:
5950 // If either operand of the select is a constant, we can fold the
5951 // comparison into the select arms, which will cause one to be
5952 // constant folded and the select turned into a bitwise or.
5953 Value *Op1 = 0, *Op2 = 0;
5954 if (LHSI->hasOneUse()) {
5955 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5956 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005957 Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005958 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005959 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005960 LHSI->getOperand(2), RHSC,
5961 I.getName()), I);
5962 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5963 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005964 Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005965 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005966 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005967 LHSI->getOperand(1), RHSC,
5968 I.getName()), I);
5969 }
5970 }
5971
5972 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005973 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005974 break;
5975 }
5976 }
5977
5978 return Changed ? &I : 0;
5979}
5980
5981Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5982 bool Changed = SimplifyCompare(I);
5983 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5984 const Type *Ty = Op0->getType();
5985
5986 // icmp X, X
5987 if (Op0 == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005988 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005989 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005990
5991 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005992 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005993
Reid Spencere4d87aa2006-12-23 06:05:41 +00005994 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005995 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005996 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5997 isa<ConstantPointerNull>(Op0)) &&
5998 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005999 isa<ConstantPointerNull>(Op1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00006000 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006001 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00006002
Reid Spencere4d87aa2006-12-23 06:05:41 +00006003 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00006004 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006005 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006006 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006007 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006008 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00006009 InsertNewInstBefore(Xor, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00006010 return BinaryOperator::CreateNot(*Context, Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006011 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006012 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006013 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006014
Reid Spencere4d87aa2006-12-23 06:05:41 +00006015 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006016 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006017 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006018 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Owen Anderson73c6b712009-07-13 20:58:05 +00006019 Instruction *Not = BinaryOperator::CreateNot(*Context,
6020 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006021 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006022 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006023 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006024 case ICmpInst::ICMP_SGT:
6025 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006026 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006027 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00006028 Instruction *Not = BinaryOperator::CreateNot(*Context,
6029 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006030 InsertNewInstBefore(Not, I);
6031 return BinaryOperator::CreateAnd(Not, Op0);
6032 }
6033 case ICmpInst::ICMP_UGE:
6034 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6035 // FALL THROUGH
6036 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Owen Anderson73c6b712009-07-13 20:58:05 +00006037 Instruction *Not = BinaryOperator::CreateNot(*Context,
6038 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006039 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006040 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006041 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006042 case ICmpInst::ICMP_SGE:
6043 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6044 // FALL THROUGH
6045 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00006046 Instruction *Not = BinaryOperator::CreateNot(*Context,
6047 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006048 InsertNewInstBefore(Not, I);
6049 return BinaryOperator::CreateOr(Not, Op0);
6050 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006051 }
Chris Lattner8b170942002-08-09 23:47:40 +00006052 }
6053
Dan Gohman1c8491e2009-04-25 17:12:48 +00006054 unsigned BitWidth = 0;
6055 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006056 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6057 else if (Ty->isIntOrIntVector())
6058 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006059
6060 bool isSignBit = false;
6061
Dan Gohman81b28ce2008-09-16 18:46:06 +00006062 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006063 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006064 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006065
Chris Lattnerb6566012008-01-05 01:18:20 +00006066 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6067 if (I.isEquality() && CI->isNullValue() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006068 match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006069 // (icmp cond A B) if cond is equality
Owen Anderson333c4002009-07-09 23:48:35 +00006070 return new ICmpInst(*Context, I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006071 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006072
Dan Gohman81b28ce2008-09-16 18:46:06 +00006073 // If we have an icmp le or icmp ge instruction, turn it into the
6074 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6075 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006076 switch (I.getPredicate()) {
6077 default: break;
6078 case ICmpInst::ICMP_ULE:
6079 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006080 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006081 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6082 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006083 case ICmpInst::ICMP_SLE:
6084 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006085 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006086 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6087 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006088 case ICmpInst::ICMP_UGE:
6089 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006090 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006091 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6092 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006093 case ICmpInst::ICMP_SGE:
6094 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006095 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006096 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6097 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006098 }
6099
Chris Lattner183661e2008-07-11 05:40:05 +00006100 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006101 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006102 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006103 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6104 }
6105
6106 // See if we can fold the comparison based on range information we can get
6107 // by checking whether bits are known to be zero or one in the input.
6108 if (BitWidth != 0) {
6109 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6110 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6111
6112 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006113 isSignBit ? APInt::getSignBit(BitWidth)
6114 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006115 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006116 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006117 if (SimplifyDemandedBits(I.getOperandUse(1),
6118 APInt::getAllOnesValue(BitWidth),
6119 Op1KnownZero, Op1KnownOne, 0))
6120 return &I;
6121
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006122 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006123 // in. Compute the Min, Max and RHS values based on the known bits. For the
6124 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006125 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6126 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6127 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6128 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6129 Op0Min, Op0Max);
6130 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6131 Op1Min, Op1Max);
6132 } else {
6133 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6134 Op0Min, Op0Max);
6135 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6136 Op1Min, Op1Max);
6137 }
6138
Chris Lattner183661e2008-07-11 05:40:05 +00006139 // If Min and Max are known to be the same, then SimplifyDemandedBits
6140 // figured out that the LHS is a constant. Just constant fold this now so
6141 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006142 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006143 return new ICmpInst(*Context, I.getPredicate(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006144 Context->getConstantInt(Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006145 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006146 return new ICmpInst(*Context, I.getPredicate(), Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006147 Context->getConstantInt(Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006148
Chris Lattner183661e2008-07-11 05:40:05 +00006149 // Based on the range information we know about the LHS, see if we can
6150 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006151 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006152 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006153 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006154 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersond672ecb2009-07-03 00:17:18 +00006155 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006156 break;
6157 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006158 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersond672ecb2009-07-03 00:17:18 +00006159 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner84dff672008-07-11 05:08:55 +00006160 break;
6161 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006162 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006163 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006164 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006165 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006166 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006167 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006168 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6169 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006170 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6171 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006172
6173 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6174 if (CI->isMinValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006175 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Owen Anderson73c6b712009-07-13 20:58:05 +00006176 Context->getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006177 }
Chris Lattner84dff672008-07-11 05:08:55 +00006178 break;
6179 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006180 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006181 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006182 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006183 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006184
6185 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006186 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006187 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6188 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006189 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6190 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006191
6192 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6193 if (CI->isMaxValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006194 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006195 Context->getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006196 }
Chris Lattner84dff672008-07-11 05:08:55 +00006197 break;
6198 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006199 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Andersond672ecb2009-07-03 00:17:18 +00006200 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006201 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Andersond672ecb2009-07-03 00:17:18 +00006202 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006203 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006204 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006205 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6206 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006207 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6208 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006209 }
Chris Lattner84dff672008-07-11 05:08:55 +00006210 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006211 case ICmpInst::ICMP_SGT:
6212 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006213 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006214 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006215 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006216
6217 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006218 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006219 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6220 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006221 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6222 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006223 }
6224 break;
6225 case ICmpInst::ICMP_SGE:
6226 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6227 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006228 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006229 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006230 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006231 break;
6232 case ICmpInst::ICMP_SLE:
6233 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6234 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006235 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006236 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006237 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006238 break;
6239 case ICmpInst::ICMP_UGE:
6240 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6241 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006242 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006243 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006244 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006245 break;
6246 case ICmpInst::ICMP_ULE:
6247 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6248 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006249 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006250 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006251 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006252 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006253 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006254
6255 // Turn a signed comparison into an unsigned one if both operands
6256 // are known to have the same sign.
6257 if (I.isSignedPredicate() &&
6258 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6259 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Owen Anderson333c4002009-07-09 23:48:35 +00006260 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006261 }
6262
6263 // Test if the ICmpInst instruction is used exclusively by a select as
6264 // part of a minimum or maximum operation. If so, refrain from doing
6265 // any other folding. This helps out other analyses which understand
6266 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6267 // and CodeGen. And in this case, at least one of the comparison
6268 // operands has at least one user besides the compare (the select),
6269 // which would often largely negate the benefit of folding anyway.
6270 if (I.hasOneUse())
6271 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6272 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6273 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6274 return 0;
6275
6276 // See if we are doing a comparison between a constant and an instruction that
6277 // can be folded into the comparison.
6278 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006279 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006280 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006281 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006282 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006283 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6284 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006285 }
6286
Chris Lattner01deb9d2007-04-03 17:43:25 +00006287 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006288 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6289 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6290 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006291 case Instruction::GetElementPtr:
6292 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006293 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006294 bool isAllZeros = true;
6295 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6296 if (!isa<Constant>(LHSI->getOperand(i)) ||
6297 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6298 isAllZeros = false;
6299 break;
6300 }
6301 if (isAllZeros)
Owen Anderson333c4002009-07-09 23:48:35 +00006302 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006303 Context->getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006304 }
6305 break;
6306
Chris Lattner6970b662005-04-23 15:31:55 +00006307 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006308 // Only fold icmp into the PHI if the phi and fcmp are in the same
6309 // block. If in the same block, we're encouraging jump threading. If
6310 // not, we are just pessimizing the code by making an i1 phi.
6311 if (LHSI->getParent() == I.getParent())
6312 if (Instruction *NV = FoldOpIntoPhi(I))
6313 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006314 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006315 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006316 // If either operand of the select is a constant, we can fold the
6317 // comparison into the select arms, which will cause one to be
6318 // constant folded and the select turned into a bitwise or.
6319 Value *Op1 = 0, *Op2 = 0;
6320 if (LHSI->hasOneUse()) {
6321 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6322 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006323 Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006324 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006325 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006326 LHSI->getOperand(2), RHSC,
6327 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006328 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6329 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006330 Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006331 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006332 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006333 LHSI->getOperand(1), RHSC,
6334 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006335 }
6336 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006337
Chris Lattner6970b662005-04-23 15:31:55 +00006338 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006339 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006340 break;
6341 }
Chris Lattner4802d902007-04-06 18:57:34 +00006342 case Instruction::Malloc:
6343 // If we have (malloc != null), and if the malloc has a single use, we
6344 // can assume it is successful and remove the malloc.
6345 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6346 AddToWorkList(LHSI);
Owen Andersond672ecb2009-07-03 00:17:18 +00006347 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006348 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006349 }
6350 break;
6351 }
Chris Lattner6970b662005-04-23 15:31:55 +00006352 }
6353
Reid Spencere4d87aa2006-12-23 06:05:41 +00006354 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006355 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006356 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006357 return NI;
6358 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006359 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6360 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006361 return NI;
6362
Reid Spencere4d87aa2006-12-23 06:05:41 +00006363 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006364 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6365 // now.
6366 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6367 if (isa<PointerType>(Op0->getType()) &&
6368 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006369 // We keep moving the cast from the left operand over to the right
6370 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006371 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006372
Chris Lattner57d86372007-01-06 01:45:59 +00006373 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6374 // so eliminate it as well.
6375 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6376 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006377
Chris Lattnerde90b762003-11-03 04:25:02 +00006378 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006379 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006380 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006381 Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006382 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006383 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006384 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006385 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006386 }
Owen Anderson333c4002009-07-09 23:48:35 +00006387 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006388 }
Chris Lattner57d86372007-01-06 01:45:59 +00006389 }
6390
6391 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006392 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006393 // This comes up when you have code like
6394 // int X = A < B;
6395 // if (X) ...
6396 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006397 // with a constant or another cast from the same type.
6398 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006399 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006400 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006401 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006402
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006403 // See if it's the same type of instruction on the left and right.
6404 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6405 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006406 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006407 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006408 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006409 default: break;
6410 case Instruction::Add:
6411 case Instruction::Sub:
6412 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006413 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Owen Anderson333c4002009-07-09 23:48:35 +00006414 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006415 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006416 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6417 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6418 if (CI->getValue().isSignBit()) {
6419 ICmpInst::Predicate Pred = I.isSignedPredicate()
6420 ? I.getUnsignedPredicate()
6421 : I.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006422 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006423 Op1I->getOperand(0));
6424 }
6425
6426 if (CI->getValue().isMaxSignedValue()) {
6427 ICmpInst::Predicate Pred = I.isSignedPredicate()
6428 ? I.getUnsignedPredicate()
6429 : I.getSignedPredicate();
6430 Pred = I.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006431 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006432 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006433 }
6434 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006435 break;
6436 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006437 if (!I.isEquality())
6438 break;
6439
Nick Lewycky5d52c452008-08-21 05:56:10 +00006440 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6441 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6442 // Mask = -1 >> count-trailing-zeros(Cst).
6443 if (!CI->isZero() && !CI->isOne()) {
6444 const APInt &AP = CI->getValue();
Owen Andersond672ecb2009-07-03 00:17:18 +00006445 ConstantInt *Mask = Context->getConstantInt(
Nick Lewycky5d52c452008-08-21 05:56:10 +00006446 APInt::getLowBitsSet(AP.getBitWidth(),
6447 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006448 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006449 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6450 Mask);
6451 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6452 Mask);
6453 InsertNewInstBefore(And1, I);
6454 InsertNewInstBefore(And2, I);
Owen Anderson333c4002009-07-09 23:48:35 +00006455 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006456 }
6457 }
6458 break;
6459 }
6460 }
6461 }
6462 }
6463
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006464 // ~x < ~y --> y < x
6465 { Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006466 if (match(Op0, m_Not(m_Value(A)), *Context) &&
6467 match(Op1, m_Not(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006468 return new ICmpInst(*Context, I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006469 }
6470
Chris Lattner65b72ba2006-09-18 04:22:48 +00006471 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006472 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006473
6474 // -x == -y --> x == y
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006475 if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6476 match(Op1, m_Neg(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006477 return new ICmpInst(*Context, I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006478
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006479 if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006480 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6481 Value *OtherVal = A == Op1 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006482 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006483 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006484 }
6485
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006486 if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006487 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006488 ConstantInt *C1, *C2;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006489 if (match(B, m_ConstantInt(C1), *Context) &&
6490 match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006491 Constant *NC =
6492 Context->getConstantInt(C1->getValue() ^ C2->getValue());
Chris Lattnercb504b92008-11-16 05:38:51 +00006493 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Owen Anderson333c4002009-07-09 23:48:35 +00006494 return new ICmpInst(*Context, I.getPredicate(), A,
Chris Lattnercb504b92008-11-16 05:38:51 +00006495 InsertNewInstBefore(Xor, I));
6496 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006497
6498 // A^B == A^D -> B == D
Owen Anderson333c4002009-07-09 23:48:35 +00006499 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6500 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6501 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6502 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006503 }
6504 }
6505
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006506 if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006507 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006508 // A == (A^B) -> B == 0
6509 Value *OtherVal = A == Op0 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006510 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006511 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006512 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006513
6514 // (A-B) == A -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006515 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006516 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006517 Context->getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006518
6519 // A == (A-B) -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006520 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006521 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006522 Context->getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006523
Chris Lattner9c2328e2006-11-14 06:06:06 +00006524 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6525 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006526 match(Op0, m_And(m_Value(A), m_Value(B)), *Context) &&
6527 match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006528 Value *X = 0, *Y = 0, *Z = 0;
6529
6530 if (A == C) {
6531 X = B; Y = D; Z = A;
6532 } else if (A == D) {
6533 X = B; Y = C; Z = A;
6534 } else if (B == C) {
6535 X = A; Y = D; Z = B;
6536 } else if (B == D) {
6537 X = A; Y = C; Z = B;
6538 }
6539
6540 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006541 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6542 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006543 I.setOperand(0, Op1);
Owen Andersond672ecb2009-07-03 00:17:18 +00006544 I.setOperand(1, Context->getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006545 return &I;
6546 }
6547 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006548 }
Chris Lattner7e708292002-06-25 16:13:24 +00006549 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006550}
6551
Chris Lattner562ef782007-06-20 23:46:26 +00006552
6553/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6554/// and CmpRHS are both known to be integer constants.
6555Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6556 ConstantInt *DivRHS) {
6557 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6558 const APInt &CmpRHSV = CmpRHS->getValue();
6559
6560 // FIXME: If the operand types don't match the type of the divide
6561 // then don't attempt this transform. The code below doesn't have the
6562 // logic to deal with a signed divide and an unsigned compare (and
6563 // vice versa). This is because (x /s C1) <s C2 produces different
6564 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6565 // (x /u C1) <u C2. Simply casting the operands and result won't
6566 // work. :( The if statement below tests that condition and bails
6567 // if it finds it.
6568 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6569 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6570 return 0;
6571 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006572 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006573 if (DivIsSigned && DivRHS->isAllOnesValue())
6574 return 0; // The overflow computation also screws up here
6575 if (DivRHS->isOne())
6576 return 0; // Not worth bothering, and eliminates some funny cases
6577 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006578
6579 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6580 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6581 // C2 (CI). By solving for X we can turn this into a range check
6582 // instead of computing a divide.
Owen Andersond672ecb2009-07-03 00:17:18 +00006583 Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006584
6585 // Determine if the product overflows by seeing if the product is
6586 // not equal to the divide. Make sure we do the same kind of divide
6587 // as in the LHS instruction that we're folding.
Owen Andersond672ecb2009-07-03 00:17:18 +00006588 bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6589 Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006590
6591 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006592 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006593
Chris Lattner1dbfd482007-06-21 18:11:19 +00006594 // Figure out the interval that is being checked. For example, a comparison
6595 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6596 // Compute this interval based on the constants involved and the signedness of
6597 // the compare/divide. This computes a half-open interval, keeping track of
6598 // whether either value in the interval overflows. After analysis each
6599 // overflow variable is set to 0 if it's corresponding bound variable is valid
6600 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6601 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006602 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006603
Chris Lattner562ef782007-06-20 23:46:26 +00006604 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006605 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006606 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006607 HiOverflow = LoOverflow = ProdOV;
6608 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006609 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006610 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006611 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006612 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00006613 LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS,
6614 Context)));
Chris Lattner562ef782007-06-20 23:46:26 +00006615 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006616 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006617 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6618 HiOverflow = LoOverflow = ProdOV;
6619 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006620 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006621 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006622 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006623 HiBound = AddOne(Prod, Context);
Chris Lattnera6321b42008-10-11 22:55:00 +00006624 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6625 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006626 ConstantInt* DivNeg =
6627 cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6628 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006629 true) ? -1 : 0;
6630 }
Chris Lattner562ef782007-06-20 23:46:26 +00006631 }
Dan Gohman76491272008-02-13 22:09:18 +00006632 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006633 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006634 // e.g. X/-5 op 0 --> [-4, 5)
Owen Andersond672ecb2009-07-03 00:17:18 +00006635 LoBound = AddOne(DivRHS, Context);
6636 HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006637 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6638 HiOverflow = 1; // [INTMIN+1, overflow)
6639 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6640 }
Dan Gohman76491272008-02-13 22:09:18 +00006641 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006642 // e.g. X/-5 op 3 --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006643 HiBound = AddOne(Prod, Context);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006644 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006645 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006646 LoOverflow = AddWithOverflow(LoBound, HiBound,
6647 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006648 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006649 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6650 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006651 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006652 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006653 }
6654
Chris Lattner1dbfd482007-06-21 18:11:19 +00006655 // Dividing by a negative swaps the condition. LT <-> GT
6656 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006657 }
6658
6659 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006660 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006661 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006662 case ICmpInst::ICMP_EQ:
6663 if (LoOverflow && HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006664 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattner562ef782007-06-20 23:46:26 +00006665 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006666 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006667 ICmpInst::ICMP_UGE, X, LoBound);
6668 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006669 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006670 ICmpInst::ICMP_ULT, X, HiBound);
6671 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006672 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006673 case ICmpInst::ICMP_NE:
6674 if (LoOverflow && HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006675 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner562ef782007-06-20 23:46:26 +00006676 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006677 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006678 ICmpInst::ICMP_ULT, X, LoBound);
6679 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006680 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006681 ICmpInst::ICMP_UGE, X, HiBound);
6682 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006683 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006684 case ICmpInst::ICMP_ULT:
6685 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006686 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006687 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006688 if (LoOverflow == -1) // Low bound is less than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006689 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00006690 return new ICmpInst(*Context, Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006691 case ICmpInst::ICMP_UGT:
6692 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006693 if (HiOverflow == +1) // High bound greater than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006694 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006695 else if (HiOverflow == -1) // High bound less than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006696 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006697 if (Pred == ICmpInst::ICMP_UGT)
Owen Anderson333c4002009-07-09 23:48:35 +00006698 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006699 else
Owen Anderson333c4002009-07-09 23:48:35 +00006700 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006701 }
6702}
6703
6704
Chris Lattner01deb9d2007-04-03 17:43:25 +00006705/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6706///
6707Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6708 Instruction *LHSI,
6709 ConstantInt *RHS) {
6710 const APInt &RHSV = RHS->getValue();
6711
6712 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006713 case Instruction::Trunc:
6714 if (ICI.isEquality() && LHSI->hasOneUse()) {
6715 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6716 // of the high bits truncated out of x are known.
6717 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6718 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6719 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6720 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6721 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6722
6723 // If all the high bits are known, we can do this xform.
6724 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6725 // Pull in the high bits from known-ones set.
6726 APInt NewRHS(RHS->getValue());
6727 NewRHS.zext(SrcBits);
6728 NewRHS |= KnownOne;
Owen Anderson333c4002009-07-09 23:48:35 +00006729 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006730 Context->getConstantInt(NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006731 }
6732 }
6733 break;
6734
Duncan Sands0091bf22007-04-04 06:42:45 +00006735 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006736 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6737 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6738 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006739 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6740 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006741 Value *CompareVal = LHSI->getOperand(0);
6742
6743 // If the sign bit of the XorCST is not set, there is no change to
6744 // the operation, just stop using the Xor.
6745 if (!XorCST->getValue().isNegative()) {
6746 ICI.setOperand(0, CompareVal);
6747 AddToWorkList(LHSI);
6748 return &ICI;
6749 }
6750
6751 // Was the old condition true if the operand is positive?
6752 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6753
6754 // If so, the new one isn't.
6755 isTrueIfPositive ^= true;
6756
6757 if (isTrueIfPositive)
Owen Anderson333c4002009-07-09 23:48:35 +00006758 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006759 SubOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006760 else
Owen Anderson333c4002009-07-09 23:48:35 +00006761 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006762 AddOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006763 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006764
6765 if (LHSI->hasOneUse()) {
6766 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6767 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6768 const APInt &SignBit = XorCST->getValue();
6769 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6770 ? ICI.getUnsignedPredicate()
6771 : ICI.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006772 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006773 Context->getConstantInt(RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006774 }
6775
6776 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006777 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006778 const APInt &NotSignBit = XorCST->getValue();
6779 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6780 ? ICI.getUnsignedPredicate()
6781 : ICI.getSignedPredicate();
6782 Pred = ICI.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006783 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006784 Context->getConstantInt(RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006785 }
6786 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006787 }
6788 break;
6789 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6790 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6791 LHSI->getOperand(0)->hasOneUse()) {
6792 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6793
6794 // If the LHS is an AND of a truncating cast, we can widen the
6795 // and/compare to be the input width without changing the value
6796 // produced, eliminating a cast.
6797 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6798 // We can do this transformation if either the AND constant does not
6799 // have its sign bit set or if it is an equality comparison.
6800 // Extending a relational comparison when we're checking the sign
6801 // bit would not work.
6802 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006803 (ICI.isEquality() ||
6804 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006805 uint32_t BitWidth =
6806 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6807 APInt NewCST = AndCST->getValue();
6808 NewCST.zext(BitWidth);
6809 APInt NewCI = RHSV;
6810 NewCI.zext(BitWidth);
6811 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006812 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006813 Context->getConstantInt(NewCST),LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006814 InsertNewInstBefore(NewAnd, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006815 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
Owen Andersond672ecb2009-07-03 00:17:18 +00006816 Context->getConstantInt(NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006817 }
6818 }
6819
6820 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6821 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6822 // happens a LOT in code produced by the C front-end, for bitfield
6823 // access.
6824 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6825 if (Shift && !Shift->isShift())
6826 Shift = 0;
6827
6828 ConstantInt *ShAmt;
6829 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6830 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6831 const Type *AndTy = AndCST->getType(); // Type of the and.
6832
6833 // We can fold this as long as we can't shift unknown bits
6834 // into the mask. This can only happen with signed shift
6835 // rights, as they sign-extend.
6836 if (ShAmt) {
6837 bool CanFold = Shift->isLogicalShift();
6838 if (!CanFold) {
6839 // To test for the bad case of the signed shr, see if any
6840 // of the bits shifted in could be tested after the mask.
6841 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6842 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6843
6844 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6845 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6846 AndCST->getValue()) == 0)
6847 CanFold = true;
6848 }
6849
6850 if (CanFold) {
6851 Constant *NewCst;
6852 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006853 NewCst = Context->getConstantExprLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006854 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006855 NewCst = Context->getConstantExprShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006856
6857 // Check to see if we are shifting out any of the bits being
6858 // compared.
Owen Andersond672ecb2009-07-03 00:17:18 +00006859 if (Context->getConstantExpr(Shift->getOpcode(),
6860 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006861 // If we shifted bits out, the fold is not going to work out.
6862 // As a special case, check to see if this means that the
6863 // result is always true or false now.
6864 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersond672ecb2009-07-03 00:17:18 +00006865 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006866 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersond672ecb2009-07-03 00:17:18 +00006867 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006868 } else {
6869 ICI.setOperand(1, NewCst);
6870 Constant *NewAndCST;
6871 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006872 NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006873 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006874 NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006875 LHSI->setOperand(1, NewAndCST);
6876 LHSI->setOperand(0, Shift->getOperand(0));
6877 AddToWorkList(Shift); // Shift is dead.
6878 AddUsesToWorkList(ICI);
6879 return &ICI;
6880 }
6881 }
6882 }
6883
6884 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6885 // preferable because it allows the C<<Y expression to be hoisted out
6886 // of a loop if Y is invariant and X is not.
6887 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006888 ICI.isEquality() && !Shift->isArithmeticShift() &&
6889 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006890 // Compute C << Y.
6891 Value *NS;
6892 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006893 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006894 Shift->getOperand(1), "tmp");
6895 } else {
6896 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006897 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006898 Shift->getOperand(1), "tmp");
6899 }
6900 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6901
6902 // Compute X & (C << Y).
6903 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006904 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006905 InsertNewInstBefore(NewAnd, ICI);
6906
6907 ICI.setOperand(0, NewAnd);
6908 return &ICI;
6909 }
6910 }
6911 break;
6912
Chris Lattnera0141b92007-07-15 20:42:37 +00006913 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6914 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6915 if (!ShAmt) break;
6916
6917 uint32_t TypeBits = RHSV.getBitWidth();
6918
6919 // Check that the shift amount is in range. If not, don't perform
6920 // undefined shifts. When the shift is visited it will be
6921 // simplified.
6922 if (ShAmt->uge(TypeBits))
6923 break;
6924
6925 if (ICI.isEquality()) {
6926 // If we are comparing against bits always shifted out, the
6927 // comparison cannot succeed.
6928 Constant *Comp =
Owen Andersond672ecb2009-07-03 00:17:18 +00006929 Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6930 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006931 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6932 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersond672ecb2009-07-03 00:17:18 +00006933 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006934 return ReplaceInstUsesWith(ICI, Cst);
6935 }
6936
6937 if (LHSI->hasOneUse()) {
6938 // Otherwise strength reduce the shift into an and.
6939 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6940 Constant *Mask =
Owen Andersond672ecb2009-07-03 00:17:18 +00006941 Context->getConstantInt(APInt::getLowBitsSet(TypeBits,
6942 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006943
Chris Lattnera0141b92007-07-15 20:42:37 +00006944 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006945 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006946 Mask, LHSI->getName()+".mask");
6947 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006948 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00006949 Context->getConstantInt(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006950 }
6951 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006952
6953 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6954 bool TrueIfSigned = false;
6955 if (LHSI->hasOneUse() &&
6956 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6957 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersond672ecb2009-07-03 00:17:18 +00006958 Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006959 (TypeBits-ShAmt->getZExtValue()-1));
6960 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006961 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006962 Mask, LHSI->getName()+".mask");
6963 Value *And = InsertNewInstBefore(AndI, ICI);
6964
Owen Anderson333c4002009-07-09 23:48:35 +00006965 return new ICmpInst(*Context,
6966 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersond672ecb2009-07-03 00:17:18 +00006967 And, Context->getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006968 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006969 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006970 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006971
6972 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006973 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006974 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006975 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006976 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006977
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006978 // Check that the shift amount is in range. If not, don't perform
6979 // undefined shifts. When the shift is visited it will be
6980 // simplified.
6981 uint32_t TypeBits = RHSV.getBitWidth();
6982 if (ShAmt->uge(TypeBits))
6983 break;
6984
6985 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006986
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006987 // If we are comparing against bits always shifted out, the
6988 // comparison cannot succeed.
6989 APInt Comp = RHSV << ShAmtVal;
6990 if (LHSI->getOpcode() == Instruction::LShr)
6991 Comp = Comp.lshr(ShAmtVal);
6992 else
6993 Comp = Comp.ashr(ShAmtVal);
6994
6995 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6996 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersond672ecb2009-07-03 00:17:18 +00006997 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006998 return ReplaceInstUsesWith(ICI, Cst);
6999 }
7000
7001 // Otherwise, check to see if the bits shifted out are known to be zero.
7002 // If so, we can compare against the unshifted value:
7003 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007004 if (LHSI->hasOneUse() &&
7005 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007006 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Owen Anderson333c4002009-07-09 23:48:35 +00007007 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007008 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007009 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007010
Evan Chengf30752c2008-04-23 00:38:06 +00007011 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007012 // Otherwise strength reduce the shift into an and.
7013 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00007014 Constant *Mask = Context->getConstantInt(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007015
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007016 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007017 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007018 Mask, LHSI->getName()+".mask");
7019 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007020 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00007021 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007022 }
7023 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007024 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007025
7026 case Instruction::SDiv:
7027 case Instruction::UDiv:
7028 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7029 // Fold this div into the comparison, producing a range check.
7030 // Determine, based on the divide type, what the range is being
7031 // checked. If there is an overflow on the low or high side, remember
7032 // it, otherwise compute the range [low, hi) bounding the new value.
7033 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007034 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7035 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7036 DivRHS))
7037 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007038 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007039
7040 case Instruction::Add:
7041 // Fold: icmp pred (add, X, C1), C2
7042
7043 if (!ICI.isEquality()) {
7044 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7045 if (!LHSC) break;
7046 const APInt &LHSV = LHSC->getValue();
7047
7048 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7049 .subtract(LHSV);
7050
7051 if (ICI.isSignedPredicate()) {
7052 if (CR.getLower().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007053 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007054 Context->getConstantInt(CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007055 } else if (CR.getUpper().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007056 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007057 Context->getConstantInt(CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007058 }
7059 } else {
7060 if (CR.getLower().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007061 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007062 Context->getConstantInt(CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007063 } else if (CR.getUpper().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007064 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007065 Context->getConstantInt(CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007066 }
7067 }
7068 }
7069 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007070 }
7071
7072 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7073 if (ICI.isEquality()) {
7074 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7075
7076 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7077 // the second operand is a constant, simplify a bit.
7078 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7079 switch (BO->getOpcode()) {
7080 case Instruction::SRem:
7081 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7082 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7083 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7084 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7085 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007086 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007087 BO->getName());
7088 InsertNewInstBefore(NewRem, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007089 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
Owen Andersond672ecb2009-07-03 00:17:18 +00007090 Context->getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007091 }
7092 }
7093 break;
7094 case Instruction::Add:
7095 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7096 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7097 if (BO->hasOneUse())
Owen Anderson333c4002009-07-09 23:48:35 +00007098 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007099 Context->getConstantExprSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007100 } else if (RHSV == 0) {
7101 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7102 // efficiently invertible, or if the add has just this one use.
7103 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7104
Owen Andersond672ecb2009-07-03 00:17:18 +00007105 if (Value *NegVal = dyn_castNegVal(BOp1, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007106 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
Owen Andersond672ecb2009-07-03 00:17:18 +00007107 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007108 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007109 else if (BO->hasOneUse()) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00007110 Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007111 InsertNewInstBefore(Neg, ICI);
7112 Neg->takeName(BO);
Owen Anderson333c4002009-07-09 23:48:35 +00007113 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007114 }
7115 }
7116 break;
7117 case Instruction::Xor:
7118 // For the xor case, we can xor two constants together, eliminating
7119 // the explicit xor.
7120 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Owen Anderson333c4002009-07-09 23:48:35 +00007121 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007122 Context->getConstantExprXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007123
7124 // FALLTHROUGH
7125 case Instruction::Sub:
7126 // Replace (([sub|xor] A, B) != 0) with (A != B)
7127 if (RHSV == 0)
Owen Anderson333c4002009-07-09 23:48:35 +00007128 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007129 BO->getOperand(1));
7130 break;
7131
7132 case Instruction::Or:
7133 // If bits are being or'd in that are not present in the constant we
7134 // are comparing against, then the comparison could never succeed!
7135 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007136 Constant *NotCI = Context->getConstantExprNot(RHS);
7137 if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7138 return ReplaceInstUsesWith(ICI,
7139 Context->getConstantInt(Type::Int1Ty,
7140 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007141 }
7142 break;
7143
7144 case Instruction::And:
7145 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7146 // If bits are being compared against that are and'd out, then the
7147 // comparison can never succeed!
7148 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007149 return ReplaceInstUsesWith(ICI,
7150 Context->getConstantInt(Type::Int1Ty,
7151 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007152
7153 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7154 if (RHS == BOC && RHSV.isPowerOf2())
Owen Anderson333c4002009-07-09 23:48:35 +00007155 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007156 ICmpInst::ICMP_NE, LHSI,
Owen Andersond672ecb2009-07-03 00:17:18 +00007157 Context->getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007158
7159 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007160 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007161 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007162 Constant *Zero = Context->getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007163 ICmpInst::Predicate pred = isICMP_NE ?
7164 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Owen Anderson333c4002009-07-09 23:48:35 +00007165 return new ICmpInst(*Context, pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007166 }
7167
7168 // ((X & ~7) == 0) --> X < 8
7169 if (RHSV == 0 && isHighOnes(BOC)) {
7170 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007171 Constant *NegX = Context->getConstantExprNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007172 ICmpInst::Predicate pred = isICMP_NE ?
7173 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Owen Anderson333c4002009-07-09 23:48:35 +00007174 return new ICmpInst(*Context, pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007175 }
7176 }
7177 default: break;
7178 }
7179 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7180 // Handle icmp {eq|ne} <intrinsic>, intcst.
7181 if (II->getIntrinsicID() == Intrinsic::bswap) {
7182 AddToWorkList(II);
7183 ICI.setOperand(0, II->getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007184 ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007185 return &ICI;
7186 }
7187 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007188 }
7189 return 0;
7190}
7191
7192/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7193/// We only handle extending casts so far.
7194///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007195Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7196 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007197 Value *LHSCIOp = LHSCI->getOperand(0);
7198 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007199 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007200 Value *RHSCIOp;
7201
Chris Lattner8c756c12007-05-05 22:41:33 +00007202 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7203 // integer type is the same size as the pointer type.
7204 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7205 getTargetData().getPointerSizeInBits() ==
7206 cast<IntegerType>(DestTy)->getBitWidth()) {
7207 Value *RHSOp = 0;
7208 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007209 RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007210 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7211 RHSOp = RHSC->getOperand(0);
7212 // If the pointer types don't match, insert a bitcast.
7213 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007214 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007215 }
7216
7217 if (RHSOp)
Owen Anderson333c4002009-07-09 23:48:35 +00007218 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007219 }
7220
7221 // The code below only handles extension cast instructions, so far.
7222 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007223 if (LHSCI->getOpcode() != Instruction::ZExt &&
7224 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007225 return 0;
7226
Reid Spencere4d87aa2006-12-23 06:05:41 +00007227 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7228 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007229
Reid Spencere4d87aa2006-12-23 06:05:41 +00007230 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007231 // Not an extension from the same type?
7232 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007233 if (RHSCIOp->getType() != LHSCIOp->getType())
7234 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007235
Nick Lewycky4189a532008-01-28 03:48:02 +00007236 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007237 // and the other is a zext), then we can't handle this.
7238 if (CI->getOpcode() != LHSCI->getOpcode())
7239 return 0;
7240
Nick Lewycky4189a532008-01-28 03:48:02 +00007241 // Deal with equality cases early.
7242 if (ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007243 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007244
7245 // A signed comparison of sign extended values simplifies into a
7246 // signed comparison.
7247 if (isSignedCmp && isSignedExt)
Owen Anderson333c4002009-07-09 23:48:35 +00007248 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007249
7250 // The other three cases all fold into an unsigned comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00007251 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007252 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007253
Reid Spencere4d87aa2006-12-23 06:05:41 +00007254 // If we aren't dealing with a constant on the RHS, exit early
7255 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7256 if (!CI)
7257 return 0;
7258
7259 // Compute the constant that would happen if we truncated to SrcTy then
7260 // reextended to DestTy.
Owen Andersond672ecb2009-07-03 00:17:18 +00007261 Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7262 Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7263 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007264
7265 // If the re-extended constant didn't change...
7266 if (Res2 == CI) {
7267 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7268 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007269 // %A = sext i16 %X to i32
7270 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007271 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007272 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007273 // because %A may have negative value.
7274 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007275 // However, we allow this when the compare is EQ/NE, because they are
7276 // signless.
7277 if (isSignedExt == isSignedCmp || ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007278 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007279 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007280 }
7281
7282 // The re-extended constant changed so the constant cannot be represented
7283 // in the shorter type. Consequently, we cannot emit a simple comparison.
7284
7285 // First, handle some easy cases. We know the result cannot be equal at this
7286 // point so handle the ICI.isEquality() cases
7287 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersond672ecb2009-07-03 00:17:18 +00007288 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007289 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersond672ecb2009-07-03 00:17:18 +00007290 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007291
7292 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7293 // should have been folded away previously and not enter in here.
7294 Value *Result;
7295 if (isSignedCmp) {
7296 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007297 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00007298 Result = Context->getConstantIntFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007299 else
Owen Andersond672ecb2009-07-03 00:17:18 +00007300 Result = Context->getConstantIntTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007301 } else {
7302 // We're performing an unsigned comparison.
7303 if (isSignedExt) {
7304 // We're performing an unsigned comp with a sign extended value.
7305 // This is true if the input is >= 0. [aka >s -1]
Owen Anderson73c6b712009-07-13 20:58:05 +00007306 Constant *NegOne = Context->getAllOnesValue(SrcTy);
Owen Anderson333c4002009-07-09 23:48:35 +00007307 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7308 LHSCIOp, NegOne, ICI.getName()), ICI);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007309 } else {
7310 // Unsigned extend & unsigned compare -> always true.
Owen Andersond672ecb2009-07-03 00:17:18 +00007311 Result = Context->getConstantIntTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007312 }
7313 }
7314
7315 // Finally, return the value computed.
7316 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007317 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007318 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007319
7320 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7321 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7322 "ICmp should be folded!");
7323 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00007324 return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
Owen Anderson73c6b712009-07-13 20:58:05 +00007325 return BinaryOperator::CreateNot(*Context, Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007326}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007327
Reid Spencer832254e2007-02-02 02:16:23 +00007328Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7329 return commonShiftTransforms(I);
7330}
7331
7332Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7333 return commonShiftTransforms(I);
7334}
7335
7336Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007337 if (Instruction *R = commonShiftTransforms(I))
7338 return R;
7339
7340 Value *Op0 = I.getOperand(0);
7341
7342 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7343 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7344 if (CSI->isAllOnesValue())
7345 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007346
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007347 // See if we can turn a signed shr into an unsigned shr.
7348 if (MaskedValueIsZero(Op0,
7349 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7350 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7351
7352 // Arithmetic shifting an all-sign-bit value is a no-op.
7353 unsigned NumSignBits = ComputeNumSignBits(Op0);
7354 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7355 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007356
Chris Lattner348f6652007-12-06 01:59:46 +00007357 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007358}
7359
7360Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7361 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007362 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007363
7364 // shl X, 0 == X and shr X, 0 == X
7365 // shl 0, X == 0 and shr 0, X == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007366 if (Op1 == Context->getNullValue(Op1->getType()) ||
7367 Op0 == Context->getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007368 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007369
Reid Spencere4d87aa2006-12-23 06:05:41 +00007370 if (isa<UndefValue>(Op0)) {
7371 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007372 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007373 else // undef << X -> 0, undef >>u X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007374 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007375 }
7376 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007377 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7378 return ReplaceInstUsesWith(I, Op0);
7379 else // X << undef, X >>u undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007380 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007381 }
7382
Dan Gohman9004c8a2009-05-21 02:28:33 +00007383 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007384 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007385 return &I;
7386
Chris Lattner2eefe512004-04-09 19:05:30 +00007387 // Try to fold constant and into select arguments.
7388 if (isa<Constant>(Op0))
7389 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007390 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007391 return R;
7392
Reid Spencerb83eb642006-10-20 07:07:24 +00007393 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007394 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7395 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007396 return 0;
7397}
7398
Reid Spencerb83eb642006-10-20 07:07:24 +00007399Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007400 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007401 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007402
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007403 // See if we can simplify any instructions used by the instruction whose sole
7404 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007405 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007406
Dan Gohmana119de82009-06-14 23:30:43 +00007407 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7408 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007409 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007410 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007411 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007412 return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007413 else {
Owen Andersond672ecb2009-07-03 00:17:18 +00007414 I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007415 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007416 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007417 }
7418
7419 // ((X*C1) << C2) == (X * (C1 << C2))
7420 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7421 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7422 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007423 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007424 Context->getConstantExprShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007425
7426 // Try to fold constant and into select arguments.
7427 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7428 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7429 return R;
7430 if (isa<PHINode>(Op0))
7431 if (Instruction *NV = FoldOpIntoPhi(I))
7432 return NV;
7433
Chris Lattner8999dd32007-12-22 09:07:47 +00007434 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7435 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7436 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7437 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7438 // place. Don't try to do this transformation in this case. Also, we
7439 // require that the input operand is a shift-by-constant so that we have
7440 // confidence that the shifts will get folded together. We could do this
7441 // xform in more cases, but it is unlikely to be profitable.
7442 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7443 isa<ConstantInt>(TrOp->getOperand(1))) {
7444 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersond672ecb2009-07-03 00:17:18 +00007445 Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007446 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007447 I.getName());
7448 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7449
7450 // For logical shifts, the truncation has the effect of making the high
7451 // part of the register be zeros. Emulate this by inserting an AND to
7452 // clear the top bits as needed. This 'and' will usually be zapped by
7453 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007454 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7455 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007456 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7457
7458 // The mask we constructed says what the trunc would do if occurring
7459 // between the shifts. We want to know the effect *after* the second
7460 // shift. We know that it is a logical shift by a constant, so adjust the
7461 // mask as appropriate.
7462 if (I.getOpcode() == Instruction::Shl)
7463 MaskV <<= Op1->getZExtValue();
7464 else {
7465 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7466 MaskV = MaskV.lshr(Op1->getZExtValue());
7467 }
7468
Owen Andersond672ecb2009-07-03 00:17:18 +00007469 Instruction *And =
7470 BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV),
7471 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007472 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7473
7474 // Return the value truncated to the interesting size.
7475 return new TruncInst(And, I.getType());
7476 }
7477 }
7478
Chris Lattner4d5542c2006-01-06 07:12:35 +00007479 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007480 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7481 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7482 Value *V1, *V2;
7483 ConstantInt *CC;
7484 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007485 default: break;
7486 case Instruction::Add:
7487 case Instruction::And:
7488 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007489 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007490 // These operators commute.
7491 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007492 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007493 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7494 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007495 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007496 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007497 Op0BO->getName());
7498 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007499 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007500 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007501 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007502 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007503 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersond672ecb2009-07-03 00:17:18 +00007504 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng90b96812007-03-30 05:45:18 +00007505 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007506 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007507
Chris Lattner150f12a2005-09-18 06:30:59 +00007508 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007509 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007510 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007511 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007512 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007513 m_ConstantInt(CC)), *Context) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007514 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007515 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007516 Op0BO->getOperand(0), Op1,
7517 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007518 InsertNewInstBefore(YS, I); // (Y << C)
7519 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007520 BinaryOperator::CreateAnd(V1,
7521 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007522 V1->getName()+".mask");
7523 InsertNewInstBefore(XM, I); // X & (CC << C)
7524
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007525 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007526 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007527 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007528
Reid Spencera07cb7d2007-02-02 14:41:37 +00007529 // FALL THROUGH.
7530 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007531 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007532 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007533 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7534 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007535 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007536 Op0BO->getOperand(1), Op1,
7537 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007538 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007539 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007540 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007541 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007542 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007543 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersond672ecb2009-07-03 00:17:18 +00007544 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng90b96812007-03-30 05:45:18 +00007545 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007546 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007547
Chris Lattner13d4ab42006-05-31 21:14:00 +00007548 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007549 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7550 match(Op0BO->getOperand(0),
7551 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007552 m_ConstantInt(CC)), *Context) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007553 cast<BinaryOperator>(Op0BO->getOperand(0))
7554 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007555 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007556 Op0BO->getOperand(1), Op1,
7557 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007558 InsertNewInstBefore(YS, I); // (Y << C)
7559 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007560 BinaryOperator::CreateAnd(V1,
7561 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007562 V1->getName()+".mask");
7563 InsertNewInstBefore(XM, I); // X & (CC << C)
7564
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007565 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007566 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007567
Chris Lattner11021cb2005-09-18 05:12:10 +00007568 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007569 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007570 }
7571
7572
7573 // If the operand is an bitwise operator with a constant RHS, and the
7574 // shift is the only use, we can pull it out of the shift.
7575 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7576 bool isValid = true; // Valid only for And, Or, Xor
7577 bool highBitSet = false; // Transform if high bit of constant set?
7578
7579 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007580 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007581 case Instruction::Add:
7582 isValid = isLeftShift;
7583 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007584 case Instruction::Or:
7585 case Instruction::Xor:
7586 highBitSet = false;
7587 break;
7588 case Instruction::And:
7589 highBitSet = true;
7590 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007591 }
7592
7593 // If this is a signed shift right, and the high bit is modified
7594 // by the logical operation, do not perform the transformation.
7595 // The highBitSet boolean indicates the value of the high bit of
7596 // the constant which would cause it to be modified for this
7597 // operation.
7598 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007599 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007600 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007601
7602 if (isValid) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007603 Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007604
7605 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007606 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007607 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007608 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007609
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007610 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007611 NewRHS);
7612 }
7613 }
7614 }
7615 }
7616
Chris Lattnerad0124c2006-01-06 07:52:12 +00007617 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007618 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7619 if (ShiftOp && !ShiftOp->isShift())
7620 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007621
Reid Spencerb83eb642006-10-20 07:07:24 +00007622 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007623 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007624 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7625 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007626 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7627 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7628 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007629
Zhou Sheng4351c642007-04-02 08:20:41 +00007630 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007631
7632 const IntegerType *Ty = cast<IntegerType>(I.getType());
7633
7634 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007635 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007636 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7637 // saturates.
7638 if (AmtSum >= TypeBits) {
7639 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007640 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007641 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7642 }
7643
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007644 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersond672ecb2009-07-03 00:17:18 +00007645 Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007646 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7647 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007648 if (AmtSum >= TypeBits)
Owen Andersond672ecb2009-07-03 00:17:18 +00007649 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007650
Chris Lattnerb87056f2007-02-05 00:57:54 +00007651 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersond672ecb2009-07-03 00:17:18 +00007652 return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007653 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7654 I.getOpcode() == Instruction::LShr) {
7655 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007656 if (AmtSum >= TypeBits)
7657 AmtSum = TypeBits-1;
7658
Chris Lattnerb87056f2007-02-05 00:57:54 +00007659 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007660 BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007661 InsertNewInstBefore(Shift, I);
7662
Zhou Shenge9e03f62007-03-28 15:02:20 +00007663 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007664 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007665 }
7666
Chris Lattnerb87056f2007-02-05 00:57:54 +00007667 // Okay, if we get here, one shift must be left, and the other shift must be
7668 // right. See if the amounts are equal.
7669 if (ShiftAmt1 == ShiftAmt2) {
7670 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7671 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007672 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007673 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007674 }
7675 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7676 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007677 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007678 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007679 }
7680 // We can simplify ((X << C) >>s C) into a trunc + sext.
7681 // NOTE: we could do this for any C, but that would make 'unusual' integer
7682 // types. For now, just stick to ones well-supported by the code
7683 // generators.
7684 const Type *SExtType = 0;
7685 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007686 case 1 :
7687 case 8 :
7688 case 16 :
7689 case 32 :
7690 case 64 :
7691 case 128:
Owen Andersond672ecb2009-07-03 00:17:18 +00007692 SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007693 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007694 default: break;
7695 }
7696 if (SExtType) {
7697 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7698 InsertNewInstBefore(NewTrunc, I);
7699 return new SExtInst(NewTrunc, Ty);
7700 }
7701 // Otherwise, we can't handle it yet.
7702 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007703 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007704
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007705 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007706 if (I.getOpcode() == Instruction::Shl) {
7707 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7708 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007709 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007710 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007711 InsertNewInstBefore(Shift, I);
7712
Reid Spencer55702aa2007-03-25 21:11:44 +00007713 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007714 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007715 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007716
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007717 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007718 if (I.getOpcode() == Instruction::LShr) {
7719 assert(ShiftOp->getOpcode() == Instruction::Shl);
7720 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007721 BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007722 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007723
Reid Spencerd5e30f02007-03-26 17:18:58 +00007724 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007725 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007726 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007727
7728 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7729 } else {
7730 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007731 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007732
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007733 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007734 if (I.getOpcode() == Instruction::Shl) {
7735 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7736 ShiftOp->getOpcode() == Instruction::AShr);
7737 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007738 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersond672ecb2009-07-03 00:17:18 +00007739 Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007740 InsertNewInstBefore(Shift, I);
7741
Reid Spencer55702aa2007-03-25 21:11:44 +00007742 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007743 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007744 }
7745
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007746 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007747 if (I.getOpcode() == Instruction::LShr) {
7748 assert(ShiftOp->getOpcode() == Instruction::Shl);
7749 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007750 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007751 InsertNewInstBefore(Shift, I);
7752
Reid Spencer68d27cf2007-03-26 23:45:51 +00007753 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007754 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007755 }
7756
7757 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007758 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007759 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007760 return 0;
7761}
7762
Chris Lattnera1be5662002-05-02 17:06:02 +00007763
Chris Lattnercfd65102005-10-29 04:36:15 +00007764/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7765/// expression. If so, decompose it, returning some value X, such that Val is
7766/// X*Scale+Offset.
7767///
7768static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007769 int &Offset, LLVMContext *Context) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007770 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007771 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007772 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007773 Scale = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00007774 return Context->getConstantInt(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007775 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7776 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7777 if (I->getOpcode() == Instruction::Shl) {
7778 // This is a value scaled by '1 << the shift amt'.
7779 Scale = 1U << RHS->getZExtValue();
7780 Offset = 0;
7781 return I->getOperand(0);
7782 } else if (I->getOpcode() == Instruction::Mul) {
7783 // This value is scaled by 'RHS'.
7784 Scale = RHS->getZExtValue();
7785 Offset = 0;
7786 return I->getOperand(0);
7787 } else if (I->getOpcode() == Instruction::Add) {
7788 // We have X+C. Check to see if we really have (X*C2)+C1,
7789 // where C1 is divisible by C2.
7790 unsigned SubScale;
7791 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007792 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7793 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007794 Offset += RHS->getZExtValue();
7795 Scale = SubScale;
7796 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007797 }
7798 }
7799 }
7800
7801 // Otherwise, we can't look past this.
7802 Scale = 1;
7803 Offset = 0;
7804 return Val;
7805}
7806
7807
Chris Lattnerb3f83972005-10-24 06:03:58 +00007808/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7809/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007810Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007811 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007812 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007813
Chris Lattnerb53c2382005-10-24 06:22:12 +00007814 // Remove any uses of AI that are dead.
7815 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007816
Chris Lattnerb53c2382005-10-24 06:22:12 +00007817 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7818 Instruction *User = cast<Instruction>(*UI++);
7819 if (isInstructionTriviallyDead(User)) {
7820 while (UI != E && *UI == User)
7821 ++UI; // If this instruction uses AI more than once, don't break UI.
7822
Chris Lattnerb53c2382005-10-24 06:22:12 +00007823 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007824 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007825 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007826 }
7827 }
7828
Chris Lattnerb3f83972005-10-24 06:03:58 +00007829 // Get the type really allocated and the type casted to.
7830 const Type *AllocElTy = AI.getAllocatedType();
7831 const Type *CastElTy = PTy->getElementType();
7832 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007833
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007834 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7835 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007836 if (CastElTyAlign < AllocElTyAlign) return 0;
7837
Chris Lattner39387a52005-10-24 06:35:18 +00007838 // If the allocation has multiple uses, only promote it if we are strictly
7839 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007840 // same, we open the door to infinite loops of various kinds. (A reference
7841 // from a dbg.declare doesn't count as a use for this purpose.)
7842 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7843 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007844
Duncan Sands777d2302009-05-09 07:06:46 +00007845 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7846 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007847 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007848
Chris Lattner455fcc82005-10-29 03:19:53 +00007849 // See if we can satisfy the modulus by pulling a scale out of the array
7850 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007851 unsigned ArraySizeScale;
7852 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007853 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007854 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7855 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007856
Chris Lattner455fcc82005-10-29 03:19:53 +00007857 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7858 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007859 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7860 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007861
Chris Lattner455fcc82005-10-29 03:19:53 +00007862 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7863 Value *Amt = 0;
7864 if (Scale == 1) {
7865 Amt = NumElements;
7866 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007867 // If the allocation size is constant, form a constant mul expression
Owen Andersond672ecb2009-07-03 00:17:18 +00007868 Amt = Context->getConstantInt(Type::Int32Ty, Scale);
Reid Spencerc5b206b2006-12-31 05:48:39 +00007869 if (isa<ConstantInt>(NumElements))
Owen Andersond672ecb2009-07-03 00:17:18 +00007870 Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
Dan Gohman6de29f82009-06-15 22:12:54 +00007871 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007872 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007873 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007874 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007875 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007876 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007877 }
7878
Jeff Cohen86796be2007-04-04 16:58:57 +00007879 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007880 Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007881 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007882 Amt = InsertNewInstBefore(Tmp, AI);
7883 }
7884
Chris Lattnerb3f83972005-10-24 06:03:58 +00007885 AllocationInst *New;
7886 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +00007887 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007888 else
Owen Anderson50dead02009-07-15 23:53:25 +00007889 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007890 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007891 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007892
Dale Johannesena0a66372009-03-05 00:39:02 +00007893 // If the allocation has one real use plus a dbg.declare, just remove the
7894 // declare.
7895 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7896 EraseInstFromFunction(*DI);
7897 }
7898 // If the allocation has multiple real uses, insert a cast and change all
7899 // things that used it to use the new cast. This will also hack on CI, but it
7900 // will die soon.
7901 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007902 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007903 // New is the allocation instruction, pointer typed. AI is the original
7904 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7905 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007906 InsertNewInstBefore(NewCast, AI);
7907 AI.replaceAllUsesWith(NewCast);
7908 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007909 return ReplaceInstUsesWith(CI, New);
7910}
7911
Chris Lattner70074e02006-05-13 02:06:03 +00007912/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007913/// and return it as type Ty without inserting any new casts and without
7914/// changing the computed value. This is used by code that tries to decide
7915/// whether promoting or shrinking integer operations to wider or smaller types
7916/// will allow us to eliminate a truncate or extend.
7917///
7918/// This is a truncation operation if Ty is smaller than V->getType(), or an
7919/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007920///
7921/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7922/// should return true if trunc(V) can be computed by computing V in the smaller
7923/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7924/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7925/// efficiently truncated.
7926///
7927/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7928/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7929/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007930bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007931 unsigned CastOpc,
7932 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007933 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007934 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007935 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007936
7937 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007938 if (!I) return false;
7939
Dan Gohman6de29f82009-06-15 22:12:54 +00007940 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007941
Chris Lattner951626b2007-08-02 06:11:14 +00007942 // If this is an extension or truncate, we can often eliminate it.
7943 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7944 // If this is a cast from the destination type, we can trivially eliminate
7945 // it, and this will remove a cast overall.
7946 if (I->getOperand(0)->getType() == Ty) {
7947 // If the first operand is itself a cast, and is eliminable, do not count
7948 // this as an eliminable cast. We would prefer to eliminate those two
7949 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007950 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007951 ++NumCastsRemoved;
7952 return true;
7953 }
7954 }
7955
7956 // We can't extend or shrink something that has multiple uses: doing so would
7957 // require duplicating the instruction in general, which isn't profitable.
7958 if (!I->hasOneUse()) return false;
7959
Evan Chengf35fd542009-01-15 17:01:23 +00007960 unsigned Opc = I->getOpcode();
7961 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007962 case Instruction::Add:
7963 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007964 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007965 case Instruction::And:
7966 case Instruction::Or:
7967 case Instruction::Xor:
7968 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007969 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007970 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007971 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007972 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007973
Eli Friedman070a9812009-07-13 22:46:01 +00007974 case Instruction::UDiv:
7975 case Instruction::URem: {
7976 // UDiv and URem can be truncated if all the truncated bits are zero.
7977 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7978 uint32_t BitWidth = Ty->getScalarSizeInBits();
7979 if (BitWidth < OrigBitWidth) {
7980 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7981 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7982 MaskedValueIsZero(I->getOperand(1), Mask)) {
7983 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7984 NumCastsRemoved) &&
7985 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7986 NumCastsRemoved);
7987 }
7988 }
7989 break;
7990 }
Chris Lattner46b96052006-11-29 07:18:39 +00007991 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007992 // If we are truncating the result of this SHL, and if it's a shift of a
7993 // constant amount, we can always perform a SHL in a smaller type.
7994 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007995 uint32_t BitWidth = Ty->getScalarSizeInBits();
7996 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007997 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007998 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007999 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008000 }
8001 break;
8002 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008003 // If this is a truncate of a logical shr, we can truncate it to a smaller
8004 // lshr iff we know that the bits we would otherwise be shifting in are
8005 // already zeros.
8006 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008007 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8008 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008009 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008010 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008011 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8012 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008013 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008014 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008015 }
8016 }
Chris Lattner46b96052006-11-29 07:18:39 +00008017 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008018 case Instruction::ZExt:
8019 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008020 case Instruction::Trunc:
8021 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008022 // can safely replace it. Note that replacing it does not reduce the number
8023 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008024 if (Opc == CastOpc)
8025 return true;
8026
8027 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008028 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008029 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008030 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008031 case Instruction::Select: {
8032 SelectInst *SI = cast<SelectInst>(I);
8033 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008034 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008035 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008036 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008037 }
Chris Lattner8114b712008-06-18 04:00:49 +00008038 case Instruction::PHI: {
8039 // We can change a phi if we can change all operands.
8040 PHINode *PN = cast<PHINode>(I);
8041 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8042 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008043 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008044 return false;
8045 return true;
8046 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008047 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008048 // TODO: Can handle more cases here.
8049 break;
8050 }
8051
8052 return false;
8053}
8054
8055/// EvaluateInDifferentType - Given an expression that
8056/// CanEvaluateInDifferentType returns true for, actually insert the code to
8057/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008058Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008059 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008060 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +00008061 return Context->getConstantExprIntegerCast(C, Ty,
8062 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008063
8064 // Otherwise, it must be an instruction.
8065 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008066 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008067 unsigned Opc = I->getOpcode();
8068 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008069 case Instruction::Add:
8070 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008071 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008072 case Instruction::And:
8073 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008074 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008075 case Instruction::AShr:
8076 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008077 case Instruction::Shl:
8078 case Instruction::UDiv:
8079 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008080 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008081 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008082 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008083 break;
8084 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008085 case Instruction::Trunc:
8086 case Instruction::ZExt:
8087 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008088 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008089 // just return the source. There's no need to insert it because it is not
8090 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008091 if (I->getOperand(0)->getType() == Ty)
8092 return I->getOperand(0);
8093
Chris Lattner8114b712008-06-18 04:00:49 +00008094 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008095 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008096 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008097 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008098 case Instruction::Select: {
8099 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8100 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8101 Res = SelectInst::Create(I->getOperand(0), True, False);
8102 break;
8103 }
Chris Lattner8114b712008-06-18 04:00:49 +00008104 case Instruction::PHI: {
8105 PHINode *OPN = cast<PHINode>(I);
8106 PHINode *NPN = PHINode::Create(Ty);
8107 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8108 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8109 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8110 }
8111 Res = NPN;
8112 break;
8113 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008114 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008115 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008116 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008117 break;
8118 }
8119
Chris Lattner8114b712008-06-18 04:00:49 +00008120 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008121 return InsertNewInstBefore(Res, *I);
8122}
8123
Reid Spencer3da59db2006-11-27 01:05:10 +00008124/// @brief Implement the transforms common to all CastInst visitors.
8125Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008126 Value *Src = CI.getOperand(0);
8127
Dan Gohman23d9d272007-05-11 21:10:54 +00008128 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008129 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008130 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008131 if (Instruction::CastOps opc =
8132 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8133 // The first cast (CSrc) is eliminable so we need to fix up or replace
8134 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008135 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008136 }
8137 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008138
Reid Spencer3da59db2006-11-27 01:05:10 +00008139 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008140 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8141 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8142 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008143
8144 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008145 if (isa<PHINode>(Src))
8146 if (Instruction *NV = FoldOpIntoPhi(CI))
8147 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008148
Reid Spencer3da59db2006-11-27 01:05:10 +00008149 return 0;
8150}
8151
Chris Lattner46cd5a12009-01-09 05:44:56 +00008152/// FindElementAtOffset - Given a type and a constant offset, determine whether
8153/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008154/// the specified offset. If so, fill them into NewIndices and return the
8155/// resultant element type, otherwise return null.
8156static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8157 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008158 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008159 LLVMContext *Context) {
Chris Lattner3914f722009-01-24 01:00:13 +00008160 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008161
8162 // Start with the index over the outer type. Note that the type size
8163 // might be zero (even if the offset isn't zero) if the indexed type
8164 // is something like [0 x {int, int}]
8165 const Type *IntPtrTy = TD->getIntPtrType();
8166 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008167 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008168 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008169 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008170
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008171 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008172 if (Offset < 0) {
8173 --FirstIdx;
8174 Offset += TySize;
8175 assert(Offset >= 0);
8176 }
8177 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8178 }
8179
Owen Andersond672ecb2009-07-03 00:17:18 +00008180 NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008181
8182 // Index into the types. If we fail, set OrigBase to null.
8183 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008184 // Indexing into tail padding between struct/array elements.
8185 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008186 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008187
Chris Lattner46cd5a12009-01-09 05:44:56 +00008188 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8189 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008190 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8191 "Offset must stay within the indexed type");
8192
Chris Lattner46cd5a12009-01-09 05:44:56 +00008193 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Andersond672ecb2009-07-03 00:17:18 +00008194 NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008195
8196 Offset -= SL->getElementOffset(Elt);
8197 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008198 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008199 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008200 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersond672ecb2009-07-03 00:17:18 +00008201 NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008202 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008203 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008204 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008205 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008206 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008207 }
8208 }
8209
Chris Lattner3914f722009-01-24 01:00:13 +00008210 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008211}
8212
Chris Lattnerd3e28342007-04-27 17:44:50 +00008213/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8214Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8215 Value *Src = CI.getOperand(0);
8216
Chris Lattnerd3e28342007-04-27 17:44:50 +00008217 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008218 // If casting the result of a getelementptr instruction with no offset, turn
8219 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008220 if (GEP->hasAllZeroIndices()) {
8221 // Changing the cast operand is usually not a good idea but it is safe
8222 // here because the pointer operand is being replaced with another
8223 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00008224 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008225 CI.setOperand(0, GEP->getOperand(0));
8226 return &CI;
8227 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008228
8229 // If the GEP has a single use, and the base pointer is a bitcast, and the
8230 // GEP computes a constant offset, see if we can convert these three
8231 // instructions into fewer. This typically happens with unions and other
8232 // non-type-safe code.
8233 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8234 if (GEP->hasAllConstantIndices()) {
8235 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008236 ConstantInt *OffsetV =
8237 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008238 int64_t Offset = OffsetV->getSExtValue();
8239
8240 // Get the base pointer input of the bitcast, and the type it points to.
8241 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8242 const Type *GEPIdxTy =
8243 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008244 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008245 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008246 // If we were able to index down into an element, create the GEP
8247 // and bitcast the result. This eliminates one bitcast, potentially
8248 // two.
8249 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8250 NewIndices.begin(),
8251 NewIndices.end(), "");
8252 InsertNewInstBefore(NGEP, CI);
8253 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008254
Chris Lattner46cd5a12009-01-09 05:44:56 +00008255 if (isa<BitCastInst>(CI))
8256 return new BitCastInst(NGEP, CI.getType());
8257 assert(isa<PtrToIntInst>(CI));
8258 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008259 }
8260 }
8261 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008262 }
8263
8264 return commonCastTransforms(CI);
8265}
8266
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008267/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8268/// type like i42. We don't want to introduce operations on random non-legal
8269/// integer types where they don't already exist in the code. In the future,
8270/// we should consider making this based off target-data, so that 32-bit targets
8271/// won't get i64 operations etc.
8272static bool isSafeIntegerType(const Type *Ty) {
8273 switch (Ty->getPrimitiveSizeInBits()) {
8274 case 8:
8275 case 16:
8276 case 32:
8277 case 64:
8278 return true;
8279 default:
8280 return false;
8281 }
8282}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008283
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008284/// commonIntCastTransforms - This function implements the common transforms
8285/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008286Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8287 if (Instruction *Result = commonCastTransforms(CI))
8288 return Result;
8289
8290 Value *Src = CI.getOperand(0);
8291 const Type *SrcTy = Src->getType();
8292 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008293 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8294 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008295
Reid Spencer3da59db2006-11-27 01:05:10 +00008296 // See if we can simplify any instructions used by the LHS whose sole
8297 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008298 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008299 return &CI;
8300
8301 // If the source isn't an instruction or has more than one use then we
8302 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008303 Instruction *SrcI = dyn_cast<Instruction>(Src);
8304 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008305 return 0;
8306
Chris Lattnerc739cd62007-03-03 05:27:34 +00008307 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008308 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008309 // Only do this if the dest type is a simple type, don't convert the
8310 // expression tree to something weird like i93 unless the source is also
8311 // strange.
8312 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008313 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8314 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008315 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008316 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008317 // eliminates the cast, so it is always a win. If this is a zero-extension,
8318 // we need to do an AND to maintain the clear top-part of the computation,
8319 // so we require that the input have eliminated at least one cast. If this
8320 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008321 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008322 bool DoXForm = false;
8323 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008324 switch (CI.getOpcode()) {
8325 default:
8326 // All the others use floating point so we shouldn't actually
8327 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008328 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008329 case Instruction::Trunc:
8330 DoXForm = true;
8331 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008332 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008333 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008334 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008335 // If it's unnecessary to issue an AND to clear the high bits, it's
8336 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008337 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008338 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8339 if (MaskedValueIsZero(TryRes, Mask))
8340 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008341
8342 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008343 if (TryI->use_empty())
8344 EraseInstFromFunction(*TryI);
8345 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008346 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008347 }
Evan Chengf35fd542009-01-15 17:01:23 +00008348 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008349 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008350 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008351 // If we do not have to emit the truncate + sext pair, then it's always
8352 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008353 //
8354 // It's not safe to eliminate the trunc + sext pair if one of the
8355 // eliminated cast is a truncate. e.g.
8356 // t2 = trunc i32 t1 to i16
8357 // t3 = sext i16 t2 to i32
8358 // !=
8359 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008360 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008361 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8362 if (NumSignBits > (DestBitSize - SrcBitSize))
8363 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008364
8365 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008366 if (TryI->use_empty())
8367 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008368 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008369 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008370 }
Evan Chengf35fd542009-01-15 17:01:23 +00008371 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008372
8373 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008374 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8375 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008376 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8377 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008378 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008379 // Just replace this cast with the result.
8380 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008381
Reid Spencer3da59db2006-11-27 01:05:10 +00008382 assert(Res->getType() == DestTy);
8383 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008384 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008385 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008386 // Just replace this cast with the result.
8387 return ReplaceInstUsesWith(CI, Res);
8388 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008389 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008390
8391 // If the high bits are already zero, just replace this cast with the
8392 // result.
8393 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8394 if (MaskedValueIsZero(Res, Mask))
8395 return ReplaceInstUsesWith(CI, Res);
8396
8397 // We need to emit an AND to clear the high bits.
Owen Andersond672ecb2009-07-03 00:17:18 +00008398 Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
Chris Lattnercd1d6d52007-04-02 05:48:58 +00008399 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008400 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008401 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008402 case Instruction::SExt: {
8403 // If the high bits are already filled with sign bit, just replace this
8404 // cast with the result.
8405 unsigned NumSignBits = ComputeNumSignBits(Res);
8406 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008407 return ReplaceInstUsesWith(CI, Res);
8408
Reid Spencer3da59db2006-11-27 01:05:10 +00008409 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008410 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008411 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8412 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008413 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008414 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008415 }
8416 }
8417
8418 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8419 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8420
8421 switch (SrcI->getOpcode()) {
8422 case Instruction::Add:
8423 case Instruction::Mul:
8424 case Instruction::And:
8425 case Instruction::Or:
8426 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008427 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008428 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8429 // Don't insert two casts unless at least one can be eliminated.
8430 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008431 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman65445c52009-07-13 21:45:57 +00008432 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8433 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008434 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008435 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008436 }
8437 }
8438
8439 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8440 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8441 SrcI->getOpcode() == Instruction::Xor &&
Owen Andersond672ecb2009-07-03 00:17:18 +00008442 Op1 == Context->getConstantIntTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008443 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008444 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008445 return BinaryOperator::CreateXor(New,
8446 Context->getConstantInt(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008447 }
8448 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008449
Eli Friedman65445c52009-07-13 21:45:57 +00008450 case Instruction::Shl: {
8451 // Canonicalize trunc inside shl, if we can.
8452 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8453 if (CI && DestBitSize < SrcBitSize &&
8454 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8455 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8456 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008457 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008458 }
8459 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008460 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008461 }
8462 return 0;
8463}
8464
Chris Lattner8a9f5712007-04-11 06:57:46 +00008465Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008466 if (Instruction *Result = commonIntCastTransforms(CI))
8467 return Result;
8468
8469 Value *Src = CI.getOperand(0);
8470 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008471 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8472 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008473
8474 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00008475 if (DestBitWidth == 1 &&
8476 isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008477 Constant *One = Context->getConstantInt(Src->getType(), 1);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008478 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008479 Value *Zero = Context->getNullValue(Src->getType());
Owen Anderson333c4002009-07-09 23:48:35 +00008480 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008481 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008482
Chris Lattner4f9797d2009-03-24 18:15:30 +00008483 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8484 ConstantInt *ShAmtV = 0;
8485 Value *ShiftOp = 0;
8486 if (Src->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008487 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008488 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8489
8490 // Get a mask for the bits shifting in.
8491 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8492 if (MaskedValueIsZero(ShiftOp, Mask)) {
8493 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersond672ecb2009-07-03 00:17:18 +00008494 return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008495
8496 // Okay, we can shrink this. Truncate the input, then return a new
8497 // shift.
8498 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008499 Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008500 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008501 }
8502 }
8503
8504 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008505}
8506
Evan Chengb98a10e2008-03-24 00:21:34 +00008507/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8508/// in order to eliminate the icmp.
8509Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8510 bool DoXform) {
8511 // If we are just checking for a icmp eq of a single bit and zext'ing it
8512 // to an integer, then shift the bit to the appropriate place and then
8513 // cast to integer to avoid the comparison.
8514 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8515 const APInt &Op1CV = Op1C->getValue();
8516
8517 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8518 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8519 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8520 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8521 if (!DoXform) return ICI;
8522
8523 Value *In = ICI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00008524 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008525 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008526 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008527 In->getName()+".lobit"),
8528 CI);
8529 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008530 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008531 false/*ZExt*/, "tmp", &CI);
8532
8533 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008534 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008535 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008536 In->getName()+".not"),
8537 CI);
8538 }
8539
8540 return ReplaceInstUsesWith(CI, In);
8541 }
8542
8543
8544
8545 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8546 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8547 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8548 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8549 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8550 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8551 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8552 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8553 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8554 // This only works for EQ and NE
8555 ICI->isEquality()) {
8556 // If Op1C some other power of two, convert:
8557 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8558 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8559 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8560 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8561
8562 APInt KnownZeroMask(~KnownZero);
8563 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8564 if (!DoXform) return ICI;
8565
8566 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8567 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8568 // (X&4) == 2 --> false
8569 // (X&4) != 2 --> true
Owen Andersond672ecb2009-07-03 00:17:18 +00008570 Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8571 Res = Context->getConstantExprZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008572 return ReplaceInstUsesWith(CI, Res);
8573 }
8574
8575 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8576 Value *In = ICI->getOperand(0);
8577 if (ShiftAmt) {
8578 // Perform a logical shr by shiftamt.
8579 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008580 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersond672ecb2009-07-03 00:17:18 +00008581 Context->getConstantInt(In->getType(), ShiftAmt),
Evan Chengb98a10e2008-03-24 00:21:34 +00008582 In->getName()+".lobit"), CI);
8583 }
8584
8585 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersond672ecb2009-07-03 00:17:18 +00008586 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008587 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008588 InsertNewInstBefore(cast<Instruction>(In), CI);
8589 }
8590
8591 if (CI.getType() == In->getType())
8592 return ReplaceInstUsesWith(CI, In);
8593 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008594 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008595 }
8596 }
8597 }
8598
8599 return 0;
8600}
8601
Chris Lattner8a9f5712007-04-11 06:57:46 +00008602Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008603 // If one of the common conversion will work ..
8604 if (Instruction *Result = commonIntCastTransforms(CI))
8605 return Result;
8606
8607 Value *Src = CI.getOperand(0);
8608
Chris Lattnera84f47c2009-02-17 20:47:23 +00008609 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8610 // types and if the sizes are just right we can convert this into a logical
8611 // 'and' which will be much cheaper than the pair of casts.
8612 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8613 // Get the sizes of the types involved. We know that the intermediate type
8614 // will be smaller than A or C, but don't know the relation between A and C.
8615 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008616 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8617 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8618 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008619 // If we're actually extending zero bits, then if
8620 // SrcSize < DstSize: zext(a & mask)
8621 // SrcSize == DstSize: a & mask
8622 // SrcSize > DstSize: trunc(a) & mask
8623 if (SrcSize < DstSize) {
8624 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008625 Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008626 Instruction *And =
8627 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8628 InsertNewInstBefore(And, CI);
8629 return new ZExtInst(And, CI.getType());
8630 } else if (SrcSize == DstSize) {
8631 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008632 return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008633 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008634 } else if (SrcSize > DstSize) {
8635 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8636 InsertNewInstBefore(Trunc, CI);
8637 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008638 return BinaryOperator::CreateAnd(Trunc,
8639 Context->getConstantInt(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008640 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008641 }
8642 }
8643
Evan Chengb98a10e2008-03-24 00:21:34 +00008644 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8645 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008646
Evan Chengb98a10e2008-03-24 00:21:34 +00008647 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8648 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8649 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8650 // of the (zext icmp) will be transformed.
8651 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8652 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8653 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8654 (transformZExtICmp(LHS, CI, false) ||
8655 transformZExtICmp(RHS, CI, false))) {
8656 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8657 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008658 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008659 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008660 }
8661
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008662 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008663 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8664 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8665 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8666 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008667 if (TI0->getType() == CI.getType())
8668 return
8669 BinaryOperator::CreateAnd(TI0,
Owen Andersond672ecb2009-07-03 00:17:18 +00008670 Context->getConstantExprZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008671 }
8672
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008673 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8674 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8675 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8676 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8677 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8678 And->getOperand(1) == C)
8679 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8680 Value *TI0 = TI->getOperand(0);
8681 if (TI0->getType() == CI.getType()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008682 Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008683 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8684 InsertNewInstBefore(NewAnd, *And);
8685 return BinaryOperator::CreateXor(NewAnd, ZC);
8686 }
8687 }
8688
Reid Spencer3da59db2006-11-27 01:05:10 +00008689 return 0;
8690}
8691
Chris Lattner8a9f5712007-04-11 06:57:46 +00008692Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008693 if (Instruction *I = commonIntCastTransforms(CI))
8694 return I;
8695
Chris Lattner8a9f5712007-04-11 06:57:46 +00008696 Value *Src = CI.getOperand(0);
8697
Dan Gohman1975d032008-10-30 20:40:10 +00008698 // Canonicalize sign-extend from i1 to a select.
8699 if (Src->getType() == Type::Int1Ty)
8700 return SelectInst::Create(Src,
Owen Anderson73c6b712009-07-13 20:58:05 +00008701 Context->getAllOnesValue(CI.getType()),
Owen Andersond672ecb2009-07-03 00:17:18 +00008702 Context->getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008703
8704 // See if the value being truncated is already sign extended. If so, just
8705 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008706 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008707 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008708 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8709 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8710 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008711 unsigned NumSignBits = ComputeNumSignBits(Op);
8712
8713 if (OpBits == DestBits) {
8714 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8715 // bits, it is already ready.
8716 if (NumSignBits > DestBits-MidBits)
8717 return ReplaceInstUsesWith(CI, Op);
8718 } else if (OpBits < DestBits) {
8719 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8720 // bits, just sext from i32.
8721 if (NumSignBits > OpBits-MidBits)
8722 return new SExtInst(Op, CI.getType(), "tmp");
8723 } else {
8724 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8725 // bits, just truncate to i32.
8726 if (NumSignBits > OpBits-MidBits)
8727 return new TruncInst(Op, CI.getType(), "tmp");
8728 }
8729 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008730
8731 // If the input is a shl/ashr pair of a same constant, then this is a sign
8732 // extension from a smaller value. If we could trust arbitrary bitwidth
8733 // integers, we could turn this into a truncate to the smaller bit and then
8734 // use a sext for the whole extension. Since we don't, look deeper and check
8735 // for a truncate. If the source and dest are the same type, eliminate the
8736 // trunc and extend and just do shifts. For example, turn:
8737 // %a = trunc i32 %i to i8
8738 // %b = shl i8 %a, 6
8739 // %c = ashr i8 %b, 6
8740 // %d = sext i8 %c to i32
8741 // into:
8742 // %a = shl i32 %i, 30
8743 // %d = ashr i32 %a, 30
8744 Value *A = 0;
8745 ConstantInt *BA = 0, *CA = 0;
8746 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008747 m_ConstantInt(CA)), *Context) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008748 BA == CA && isa<TruncInst>(A)) {
8749 Value *I = cast<TruncInst>(A)->getOperand(0);
8750 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008751 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8752 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008753 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersond672ecb2009-07-03 00:17:18 +00008754 Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
Chris Lattner46bbad22008-08-06 07:35:52 +00008755 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8756 CI.getName()), CI);
8757 return BinaryOperator::CreateAShr(I, ShAmtV);
8758 }
8759 }
8760
Chris Lattnerba417832007-04-11 06:12:58 +00008761 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008762}
8763
Chris Lattnerb7530652008-01-27 05:29:54 +00008764/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8765/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008766static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008767 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008768 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008769 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008770 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8771 if (!losesInfo)
Owen Andersond672ecb2009-07-03 00:17:18 +00008772 return Context->getConstantFP(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008773 return 0;
8774}
8775
8776/// LookThroughFPExtensions - If this is an fp extension instruction, look
8777/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008778static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008779 if (Instruction *I = dyn_cast<Instruction>(V))
8780 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008781 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008782
8783 // If this value is a constant, return the constant in the smallest FP type
8784 // that can accurately represent it. This allows us to turn
8785 // (float)((double)X+2.0) into x+2.0f.
8786 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8787 if (CFP->getType() == Type::PPC_FP128Ty)
8788 return V; // No constant folding of this.
8789 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008790 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008791 return V;
8792 if (CFP->getType() == Type::DoubleTy)
8793 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008794 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008795 return V;
8796 // Don't try to shrink to various long double types.
8797 }
8798
8799 return V;
8800}
8801
8802Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8803 if (Instruction *I = commonCastTransforms(CI))
8804 return I;
8805
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008806 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008807 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008808 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008809 // many builtins (sqrt, etc).
8810 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8811 if (OpI && OpI->hasOneUse()) {
8812 switch (OpI->getOpcode()) {
8813 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008814 case Instruction::FAdd:
8815 case Instruction::FSub:
8816 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008817 case Instruction::FDiv:
8818 case Instruction::FRem:
8819 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008820 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8821 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008822 if (LHSTrunc->getType() != SrcTy &&
8823 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008824 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008825 // If the source types were both smaller than the destination type of
8826 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008827 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8828 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008829 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8830 CI.getType(), CI);
8831 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8832 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008833 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008834 }
8835 }
8836 break;
8837 }
8838 }
8839 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008840}
8841
8842Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8843 return commonCastTransforms(CI);
8844}
8845
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008846Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008847 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8848 if (OpI == 0)
8849 return commonCastTransforms(FI);
8850
8851 // fptoui(uitofp(X)) --> X
8852 // fptoui(sitofp(X)) --> X
8853 // This is safe if the intermediate type has enough bits in its mantissa to
8854 // accurately represent all values of X. For example, do not do this with
8855 // i64->float->i64. This is also safe for sitofp case, because any negative
8856 // 'X' value would cause an undefined result for the fptoui.
8857 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8858 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008859 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008860 OpI->getType()->getFPMantissaWidth())
8861 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008862
8863 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008864}
8865
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008866Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008867 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8868 if (OpI == 0)
8869 return commonCastTransforms(FI);
8870
8871 // fptosi(sitofp(X)) --> X
8872 // fptosi(uitofp(X)) --> X
8873 // This is safe if the intermediate type has enough bits in its mantissa to
8874 // accurately represent all values of X. For example, do not do this with
8875 // i64->float->i64. This is also safe for sitofp case, because any negative
8876 // 'X' value would cause an undefined result for the fptoui.
8877 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8878 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008879 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008880 OpI->getType()->getFPMantissaWidth())
8881 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008882
8883 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008884}
8885
8886Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8887 return commonCastTransforms(CI);
8888}
8889
8890Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8891 return commonCastTransforms(CI);
8892}
8893
Chris Lattnera0e69692009-03-24 18:35:40 +00008894Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8895 // If the destination integer type is smaller than the intptr_t type for
8896 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8897 // trunc to be exposed to other transforms. Don't do this for extending
8898 // ptrtoint's, because we don't know if the target sign or zero extends its
8899 // pointers.
Dan Gohman6de29f82009-06-15 22:12:54 +00008900 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008901 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8902 TD->getIntPtrType(),
8903 "tmp"), CI);
8904 return new TruncInst(P, CI.getType());
8905 }
8906
Chris Lattnerd3e28342007-04-27 17:44:50 +00008907 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008908}
8909
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008910Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008911 // If the source integer type is larger than the intptr_t type for
8912 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8913 // allows the trunc to be exposed to other transforms. Don't do this for
8914 // extending inttoptr's, because we don't know if the target sign or zero
8915 // extends to pointers.
Dan Gohman6de29f82009-06-15 22:12:54 +00008916 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008917 TD->getPointerSizeInBits()) {
8918 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8919 TD->getIntPtrType(),
8920 "tmp"), CI);
8921 return new IntToPtrInst(P, CI.getType());
8922 }
8923
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008924 if (Instruction *I = commonCastTransforms(CI))
8925 return I;
8926
8927 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8928 if (!DestPointee->isSized()) return 0;
8929
8930 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8931 ConstantInt *Cst;
8932 Value *X;
8933 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008934 m_ConstantInt(Cst)), *Context)) {
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008935 // If the source and destination operands have the same type, see if this
8936 // is a single-index GEP.
8937 if (X->getType() == CI.getType()) {
8938 // Get the size of the pointee type.
Duncan Sands777d2302009-05-09 07:06:46 +00008939 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008940
8941 // Convert the constant to intptr type.
8942 APInt Offset = Cst->getValue();
8943 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8944
8945 // If Offset is evenly divisible by Size, we can do this xform.
8946 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8947 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Dan Gohman3a7a68c2009-07-17 22:25:10 +00008948 GetElementPtrInst *GEP =
8949 GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
8950 // A gep synthesized from inttoptr+add+ptrtoint must be assumed to
8951 // potentially overflow, in the absense of further analysis.
8952 cast<GEPOperator>(GEP)->setHasNoPointerOverflow(false);
8953 return GEP;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008954 }
8955 }
8956 // TODO: Could handle other cases, e.g. where add is indexing into field of
8957 // struct etc.
8958 } else if (CI.getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008959 match(CI.getOperand(0), m_Add(m_Value(X),
8960 m_ConstantInt(Cst)), *Context)) {
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008961 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8962 // "inttoptr+GEP" instead of "add+intptr".
8963
8964 // Get the size of the pointee type.
Duncan Sands777d2302009-05-09 07:06:46 +00008965 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008966
8967 // Convert the constant to intptr type.
8968 APInt Offset = Cst->getValue();
8969 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8970
8971 // If Offset is evenly divisible by Size, we can do this xform.
8972 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8973 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8974
8975 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8976 "tmp"), CI);
Dan Gohman3a7a68c2009-07-17 22:25:10 +00008977 GetElementPtrInst *GEP =
8978 GetElementPtrInst::Create(P, Context->getConstantInt(Offset), "tmp");
8979 // A gep synthesized from inttoptr+add+ptrtoint must be assumed to
8980 // potentially overflow, in the absense of further analysis.
8981 cast<GEPOperator>(GEP)->setHasNoPointerOverflow(false);
8982 return GEP;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008983 }
8984 }
8985 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008986}
8987
Chris Lattnerd3e28342007-04-27 17:44:50 +00008988Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008989 // If the operands are integer typed then apply the integer transforms,
8990 // otherwise just apply the common ones.
8991 Value *Src = CI.getOperand(0);
8992 const Type *SrcTy = Src->getType();
8993 const Type *DestTy = CI.getType();
8994
Eli Friedman7e25d452009-07-13 20:53:00 +00008995 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008996 if (Instruction *I = commonPointerCastTransforms(CI))
8997 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008998 } else {
8999 if (Instruction *Result = commonCastTransforms(CI))
9000 return Result;
9001 }
9002
9003
9004 // Get rid of casts from one type to the same type. These are useless and can
9005 // be replaced by the operand.
9006 if (DestTy == Src->getType())
9007 return ReplaceInstUsesWith(CI, Src);
9008
Reid Spencer3da59db2006-11-27 01:05:10 +00009009 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00009010 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9011 const Type *DstElTy = DstPTy->getElementType();
9012 const Type *SrcElTy = SrcPTy->getElementType();
9013
Nate Begeman83ad90a2008-03-31 00:22:16 +00009014 // If the address spaces don't match, don't eliminate the bitcast, which is
9015 // required for changing types.
9016 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9017 return 0;
9018
Chris Lattnerd3e28342007-04-27 17:44:50 +00009019 // If we are casting a malloc or alloca to a pointer to a type of the same
9020 // size, rewrite the allocation instruction to allocate the "right" type.
9021 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9022 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9023 return V;
9024
Chris Lattnerd717c182007-05-05 22:32:24 +00009025 // If the source and destination are pointers, and this cast is equivalent
9026 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00009027 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Andersond672ecb2009-07-03 00:17:18 +00009028 Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
Chris Lattnerd3e28342007-04-27 17:44:50 +00009029 unsigned NumZeros = 0;
9030 while (SrcElTy != DstElTy &&
9031 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9032 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9033 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9034 ++NumZeros;
9035 }
Chris Lattner4e998b22004-09-29 05:07:12 +00009036
Chris Lattnerd3e28342007-04-27 17:44:50 +00009037 // If we found a path from the src to dest, create the getelementptr now.
9038 if (SrcElTy == DstElTy) {
9039 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00009040 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
9041 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00009042 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009043 }
Chris Lattner24c8e382003-07-24 17:35:25 +00009044
Reid Spencer3da59db2006-11-27 01:05:10 +00009045 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9046 if (SVI->hasOneUse()) {
9047 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9048 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009049 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009050 cast<VectorType>(DestTy)->getNumElements() ==
9051 SVI->getType()->getNumElements() &&
9052 SVI->getType()->getNumElements() ==
9053 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009054 CastInst *Tmp;
9055 // If either of the operands is a cast from CI.getType(), then
9056 // evaluating the shuffle in the casted destination's type will allow
9057 // us to eliminate at least one cast.
9058 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9059 Tmp->getOperand(0)->getType() == DestTy) ||
9060 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9061 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009062 Value *LHS = InsertCastBefore(Instruction::BitCast,
9063 SVI->getOperand(0), DestTy, CI);
9064 Value *RHS = InsertCastBefore(Instruction::BitCast,
9065 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009066 // Return a new shuffle vector. Use the same element ID's, as we
9067 // know the vector types match #elts.
9068 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009069 }
9070 }
9071 }
9072 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009073 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009074}
9075
Chris Lattnere576b912004-04-09 23:46:01 +00009076/// GetSelectFoldableOperands - We want to turn code that looks like this:
9077/// %C = or %A, %B
9078/// %D = select %cond, %C, %A
9079/// into:
9080/// %C = select %cond, %B, 0
9081/// %D = or %A, %C
9082///
9083/// Assuming that the specified instruction is an operand to the select, return
9084/// a bitmask indicating which operands of this instruction are foldable if they
9085/// equal the other incoming value of the select.
9086///
9087static unsigned GetSelectFoldableOperands(Instruction *I) {
9088 switch (I->getOpcode()) {
9089 case Instruction::Add:
9090 case Instruction::Mul:
9091 case Instruction::And:
9092 case Instruction::Or:
9093 case Instruction::Xor:
9094 return 3; // Can fold through either operand.
9095 case Instruction::Sub: // Can only fold on the amount subtracted.
9096 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009097 case Instruction::LShr:
9098 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009099 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009100 default:
9101 return 0; // Cannot fold
9102 }
9103}
9104
9105/// GetSelectFoldableConstant - For the same transformation as the previous
9106/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009107static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009108 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009109 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009110 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009111 case Instruction::Add:
9112 case Instruction::Sub:
9113 case Instruction::Or:
9114 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009115 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009116 case Instruction::LShr:
9117 case Instruction::AShr:
Owen Andersond672ecb2009-07-03 00:17:18 +00009118 return Context->getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009119 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00009120 return Context->getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009121 case Instruction::Mul:
Owen Andersond672ecb2009-07-03 00:17:18 +00009122 return Context->getConstantInt(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009123 }
9124}
9125
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009126/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9127/// have the same opcode and only one use each. Try to simplify this.
9128Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9129 Instruction *FI) {
9130 if (TI->getNumOperands() == 1) {
9131 // If this is a non-volatile load or a cast from the same type,
9132 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009133 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009134 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9135 return 0;
9136 } else {
9137 return 0; // unknown unary op.
9138 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009139
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009140 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009141 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9142 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009143 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009144 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009145 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009146 }
9147
Reid Spencer832254e2007-02-02 02:16:23 +00009148 // Only handle binary operators here.
9149 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009150 return 0;
9151
9152 // Figure out if the operations have any operands in common.
9153 Value *MatchOp, *OtherOpT, *OtherOpF;
9154 bool MatchIsOpZero;
9155 if (TI->getOperand(0) == FI->getOperand(0)) {
9156 MatchOp = TI->getOperand(0);
9157 OtherOpT = TI->getOperand(1);
9158 OtherOpF = FI->getOperand(1);
9159 MatchIsOpZero = true;
9160 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9161 MatchOp = TI->getOperand(1);
9162 OtherOpT = TI->getOperand(0);
9163 OtherOpF = FI->getOperand(0);
9164 MatchIsOpZero = false;
9165 } else if (!TI->isCommutative()) {
9166 return 0;
9167 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9168 MatchOp = TI->getOperand(0);
9169 OtherOpT = TI->getOperand(1);
9170 OtherOpF = FI->getOperand(0);
9171 MatchIsOpZero = true;
9172 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9173 MatchOp = TI->getOperand(1);
9174 OtherOpT = TI->getOperand(0);
9175 OtherOpF = FI->getOperand(1);
9176 MatchIsOpZero = true;
9177 } else {
9178 return 0;
9179 }
9180
9181 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009182 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9183 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009184 InsertNewInstBefore(NewSI, SI);
9185
9186 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9187 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009188 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009189 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009190 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009191 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009192 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009193 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009194}
9195
Evan Chengde621922009-03-31 20:42:45 +00009196static bool isSelect01(Constant *C1, Constant *C2) {
9197 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9198 if (!C1I)
9199 return false;
9200 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9201 if (!C2I)
9202 return false;
9203 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9204}
9205
9206/// FoldSelectIntoOp - Try fold the select into one of the operands to
9207/// facilitate further optimization.
9208Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9209 Value *FalseVal) {
9210 // See the comment above GetSelectFoldableOperands for a description of the
9211 // transformation we are doing here.
9212 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9213 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9214 !isa<Constant>(FalseVal)) {
9215 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9216 unsigned OpToFold = 0;
9217 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9218 OpToFold = 1;
9219 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9220 OpToFold = 2;
9221 }
9222
9223 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009224 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009225 Value *OOp = TVI->getOperand(2-OpToFold);
9226 // Avoid creating select between 2 constants unless it's selecting
9227 // between 0 and 1.
9228 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9229 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9230 InsertNewInstBefore(NewSel, SI);
9231 NewSel->takeName(TVI);
9232 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9233 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009234 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009235 }
9236 }
9237 }
9238 }
9239 }
9240
9241 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9242 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9243 !isa<Constant>(TrueVal)) {
9244 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9245 unsigned OpToFold = 0;
9246 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9247 OpToFold = 1;
9248 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9249 OpToFold = 2;
9250 }
9251
9252 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009253 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009254 Value *OOp = FVI->getOperand(2-OpToFold);
9255 // Avoid creating select between 2 constants unless it's selecting
9256 // between 0 and 1.
9257 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9258 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9259 InsertNewInstBefore(NewSel, SI);
9260 NewSel->takeName(FVI);
9261 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9262 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009263 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009264 }
9265 }
9266 }
9267 }
9268 }
9269
9270 return 0;
9271}
9272
Dan Gohman81b28ce2008-09-16 18:46:06 +00009273/// visitSelectInstWithICmp - Visit a SelectInst that has an
9274/// ICmpInst as its first operand.
9275///
9276Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9277 ICmpInst *ICI) {
9278 bool Changed = false;
9279 ICmpInst::Predicate Pred = ICI->getPredicate();
9280 Value *CmpLHS = ICI->getOperand(0);
9281 Value *CmpRHS = ICI->getOperand(1);
9282 Value *TrueVal = SI.getTrueValue();
9283 Value *FalseVal = SI.getFalseValue();
9284
9285 // Check cases where the comparison is with a constant that
9286 // can be adjusted to fit the min/max idiom. We may edit ICI in
9287 // place here, so make sure the select is the only user.
9288 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009289 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009290 switch (Pred) {
9291 default: break;
9292 case ICmpInst::ICMP_ULT:
9293 case ICmpInst::ICMP_SLT: {
9294 // X < MIN ? T : F --> F
9295 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9296 return ReplaceInstUsesWith(SI, FalseVal);
9297 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009298 Constant *AdjustedRHS = SubOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009299 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9300 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9301 Pred = ICmpInst::getSwappedPredicate(Pred);
9302 CmpRHS = AdjustedRHS;
9303 std::swap(FalseVal, TrueVal);
9304 ICI->setPredicate(Pred);
9305 ICI->setOperand(1, CmpRHS);
9306 SI.setOperand(1, TrueVal);
9307 SI.setOperand(2, FalseVal);
9308 Changed = true;
9309 }
9310 break;
9311 }
9312 case ICmpInst::ICMP_UGT:
9313 case ICmpInst::ICMP_SGT: {
9314 // X > MAX ? T : F --> F
9315 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9316 return ReplaceInstUsesWith(SI, FalseVal);
9317 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009318 Constant *AdjustedRHS = AddOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009319 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9320 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9321 Pred = ICmpInst::getSwappedPredicate(Pred);
9322 CmpRHS = AdjustedRHS;
9323 std::swap(FalseVal, TrueVal);
9324 ICI->setPredicate(Pred);
9325 ICI->setOperand(1, CmpRHS);
9326 SI.setOperand(1, TrueVal);
9327 SI.setOperand(2, FalseVal);
9328 Changed = true;
9329 }
9330 break;
9331 }
9332 }
9333
Dan Gohman1975d032008-10-30 20:40:10 +00009334 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9335 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009336 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009337 if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9338 match(FalseVal, m_ConstantInt<0>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009339 Pred = ICI->getPredicate();
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009340 else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9341 match(FalseVal, m_ConstantInt<-1>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009342 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9343
Dan Gohman1975d032008-10-30 20:40:10 +00009344 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9345 // If we are just checking for a icmp eq of a single bit and zext'ing it
9346 // to an integer, then shift the bit to the appropriate place and then
9347 // cast to integer to avoid the comparison.
9348 const APInt &Op1CV = CI->getValue();
9349
9350 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9351 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9352 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009353 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009354 Value *In = ICI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00009355 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009356 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009357 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9358 In->getName()+".lobit"),
9359 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009360 if (In->getType() != SI.getType())
9361 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009362 true/*SExt*/, "tmp", ICI);
9363
9364 if (Pred == ICmpInst::ICMP_SGT)
Owen Anderson73c6b712009-07-13 20:58:05 +00009365 In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
Dan Gohman1975d032008-10-30 20:40:10 +00009366 In->getName()+".not"), *ICI);
9367
9368 return ReplaceInstUsesWith(SI, In);
9369 }
9370 }
9371 }
9372
Dan Gohman81b28ce2008-09-16 18:46:06 +00009373 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9374 // Transform (X == Y) ? X : Y -> Y
9375 if (Pred == ICmpInst::ICMP_EQ)
9376 return ReplaceInstUsesWith(SI, FalseVal);
9377 // Transform (X != Y) ? X : Y -> X
9378 if (Pred == ICmpInst::ICMP_NE)
9379 return ReplaceInstUsesWith(SI, TrueVal);
9380 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9381
9382 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9383 // Transform (X == Y) ? Y : X -> X
9384 if (Pred == ICmpInst::ICMP_EQ)
9385 return ReplaceInstUsesWith(SI, FalseVal);
9386 // Transform (X != Y) ? Y : X -> Y
9387 if (Pred == ICmpInst::ICMP_NE)
9388 return ReplaceInstUsesWith(SI, TrueVal);
9389 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9390 }
9391
9392 /// NOTE: if we wanted to, this is where to detect integer ABS
9393
9394 return Changed ? &SI : 0;
9395}
9396
Chris Lattner3d69f462004-03-12 05:52:32 +00009397Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009398 Value *CondVal = SI.getCondition();
9399 Value *TrueVal = SI.getTrueValue();
9400 Value *FalseVal = SI.getFalseValue();
9401
9402 // select true, X, Y -> X
9403 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009404 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009405 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009406
9407 // select C, X, X -> X
9408 if (TrueVal == FalseVal)
9409 return ReplaceInstUsesWith(SI, TrueVal);
9410
Chris Lattnere87597f2004-10-16 18:11:37 +00009411 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9412 return ReplaceInstUsesWith(SI, FalseVal);
9413 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9414 return ReplaceInstUsesWith(SI, TrueVal);
9415 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9416 if (isa<Constant>(TrueVal))
9417 return ReplaceInstUsesWith(SI, TrueVal);
9418 else
9419 return ReplaceInstUsesWith(SI, FalseVal);
9420 }
9421
Reid Spencer4fe16d62007-01-11 18:21:29 +00009422 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009423 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009424 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009425 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009426 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009427 } else {
9428 // Change: A = select B, false, C --> A = and !B, C
9429 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009430 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009431 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009432 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009433 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009434 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009435 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009436 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009437 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009438 } else {
9439 // Change: A = select B, C, true --> A = or !B, C
9440 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009441 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009442 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009443 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009444 }
9445 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009446
9447 // select a, b, a -> a&b
9448 // select a, a, b -> a|b
9449 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009450 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009451 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009452 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009453 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009454
Chris Lattner2eefe512004-04-09 19:05:30 +00009455 // Selecting between two integer constants?
9456 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9457 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009458 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009459 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009460 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009461 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009462 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009463 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009464 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009465 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009466 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009467 }
Chris Lattner457dd822004-06-09 07:59:58 +00009468
Reid Spencere4d87aa2006-12-23 06:05:41 +00009469 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009470 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009471 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009472 // non-constant value, eliminate this whole mess. This corresponds to
9473 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009474 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009475 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009476 cast<Constant>(IC->getOperand(1))->isNullValue())
9477 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9478 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009479 isa<ConstantInt>(ICA->getOperand(1)) &&
9480 (ICA->getOperand(1) == TrueValC ||
9481 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009482 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9483 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009484 // know whether we have a icmp_ne or icmp_eq and whether the
9485 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009486 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009487 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009488 Value *V = ICA;
9489 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009490 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009491 Instruction::Xor, V, ICA->getOperand(1)), SI);
9492 return ReplaceInstUsesWith(SI, V);
9493 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009494 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009495 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009496
9497 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009498 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9499 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009500 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009501 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9502 // This is not safe in general for floating point:
9503 // consider X== -0, Y== +0.
9504 // It becomes safe if either operand is a nonzero constant.
9505 ConstantFP *CFPt, *CFPf;
9506 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9507 !CFPt->getValueAPF().isZero()) ||
9508 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9509 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009510 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009511 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009512 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009513 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009514 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009515 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009516
Reid Spencere4d87aa2006-12-23 06:05:41 +00009517 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009518 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009519 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9520 // This is not safe in general for floating point:
9521 // consider X== -0, Y== +0.
9522 // It becomes safe if either operand is a nonzero constant.
9523 ConstantFP *CFPt, *CFPf;
9524 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9525 !CFPt->getValueAPF().isZero()) ||
9526 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9527 !CFPf->getValueAPF().isZero()))
9528 return ReplaceInstUsesWith(SI, FalseVal);
9529 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009530 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009531 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9532 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009533 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009534 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009535 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009536 }
9537
9538 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009539 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9540 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9541 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009542
Chris Lattner87875da2005-01-13 22:52:24 +00009543 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9544 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9545 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009546 Instruction *AddOp = 0, *SubOp = 0;
9547
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009548 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9549 if (TI->getOpcode() == FI->getOpcode())
9550 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9551 return IV;
9552
9553 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9554 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009555 if ((TI->getOpcode() == Instruction::Sub &&
9556 FI->getOpcode() == Instruction::Add) ||
9557 (TI->getOpcode() == Instruction::FSub &&
9558 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009559 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009560 } else if ((FI->getOpcode() == Instruction::Sub &&
9561 TI->getOpcode() == Instruction::Add) ||
9562 (FI->getOpcode() == Instruction::FSub &&
9563 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009564 AddOp = TI; SubOp = FI;
9565 }
9566
9567 if (AddOp) {
9568 Value *OtherAddOp = 0;
9569 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9570 OtherAddOp = AddOp->getOperand(1);
9571 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9572 OtherAddOp = AddOp->getOperand(0);
9573 }
9574
9575 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009576 // So at this point we know we have (Y -> OtherAddOp):
9577 // select C, (add X, Y), (sub X, Z)
9578 Value *NegVal; // Compute -Z
9579 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009580 NegVal = Context->getConstantExprNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009581 } else {
9582 NegVal = InsertNewInstBefore(
Owen Anderson0a5372e2009-07-13 04:09:18 +00009583 BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9584 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009585 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009586
9587 Value *NewTrueOp = OtherAddOp;
9588 Value *NewFalseOp = NegVal;
9589 if (AddOp != TI)
9590 std::swap(NewTrueOp, NewFalseOp);
9591 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009592 SelectInst::Create(CondVal, NewTrueOp,
9593 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009594
9595 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009596 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009597 }
9598 }
9599 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009600
Chris Lattnere576b912004-04-09 23:46:01 +00009601 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009602 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009603 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9604 if (FoldI)
9605 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009606 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009607
9608 if (BinaryOperator::isNot(CondVal)) {
9609 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9610 SI.setOperand(1, FalseVal);
9611 SI.setOperand(2, TrueVal);
9612 return &SI;
9613 }
9614
Chris Lattner3d69f462004-03-12 05:52:32 +00009615 return 0;
9616}
9617
Dan Gohmaneee962e2008-04-10 18:43:06 +00009618/// EnforceKnownAlignment - If the specified pointer points to an object that
9619/// we control, modify the object's alignment to PrefAlign. This isn't
9620/// often possible though. If alignment is important, a more reliable approach
9621/// is to simply align all global variables and allocation instructions to
9622/// their preferred alignment from the beginning.
9623///
9624static unsigned EnforceKnownAlignment(Value *V,
9625 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009626
Dan Gohmaneee962e2008-04-10 18:43:06 +00009627 User *U = dyn_cast<User>(V);
9628 if (!U) return Align;
9629
Dan Gohmanca178902009-07-17 20:47:02 +00009630 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009631 default: break;
9632 case Instruction::BitCast:
9633 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9634 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009635 // If all indexes are zero, it is just the alignment of the base pointer.
9636 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009637 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009638 if (!isa<Constant>(*i) ||
9639 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009640 AllZeroOperands = false;
9641 break;
9642 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009643
9644 if (AllZeroOperands) {
9645 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009646 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009647 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009648 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009649 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009650 }
9651
9652 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9653 // If there is a large requested alignment and we can, bump up the alignment
9654 // of the global.
9655 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009656 if (GV->getAlignment() >= PrefAlign)
9657 Align = GV->getAlignment();
9658 else {
9659 GV->setAlignment(PrefAlign);
9660 Align = PrefAlign;
9661 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009662 }
9663 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9664 // If there is a requested alignment and if this is an alloca, round up. We
9665 // don't do this for malloc, because some systems can't respect the request.
9666 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009667 if (AI->getAlignment() >= PrefAlign)
9668 Align = AI->getAlignment();
9669 else {
9670 AI->setAlignment(PrefAlign);
9671 Align = PrefAlign;
9672 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009673 }
9674 }
9675
9676 return Align;
9677}
9678
9679/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9680/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9681/// and it is more than the alignment of the ultimate object, see if we can
9682/// increase the alignment of the ultimate object, making this check succeed.
9683unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9684 unsigned PrefAlign) {
9685 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9686 sizeof(PrefAlign) * CHAR_BIT;
9687 APInt Mask = APInt::getAllOnesValue(BitWidth);
9688 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9689 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9690 unsigned TrailZ = KnownZero.countTrailingOnes();
9691 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9692
9693 if (PrefAlign > Align)
9694 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9695
9696 // We don't need to make any adjustment.
9697 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009698}
9699
Chris Lattnerf497b022008-01-13 23:50:23 +00009700Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009701 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009702 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009703 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009704 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009705
9706 if (CopyAlign < MinAlign) {
Owen Andersona547b472009-07-09 18:36:20 +00009707 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9708 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009709 return MI;
9710 }
9711
9712 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9713 // load/store.
9714 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9715 if (MemOpLength == 0) return 0;
9716
Chris Lattner37ac6082008-01-14 00:28:35 +00009717 // Source and destination pointer types are always "i8*" for intrinsic. See
9718 // if the size is something we can handle with a single primitive load/store.
9719 // A single load+store correctly handles overlapping memory in the memmove
9720 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009721 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009722 if (Size == 0) return MI; // Delete this mem transfer.
9723
9724 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009725 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009726
Chris Lattner37ac6082008-01-14 00:28:35 +00009727 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009728 Type *NewPtrTy =
9729 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009730
9731 // Memcpy forces the use of i8* for the source and destination. That means
9732 // that if you're using memcpy to move one double around, you'll get a cast
9733 // from double* to i8*. We'd much rather use a double load+store rather than
9734 // an i64 load+store, here because this improves the odds that the source or
9735 // dest address will be promotable. See if we can find a better type than the
9736 // integer datatype.
9737 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9738 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9739 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9740 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9741 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009742 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009743 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9744 if (STy->getNumElements() == 1)
9745 SrcETy = STy->getElementType(0);
9746 else
9747 break;
9748 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9749 if (ATy->getNumElements() == 1)
9750 SrcETy = ATy->getElementType();
9751 else
9752 break;
9753 } else
9754 break;
9755 }
9756
Dan Gohman8f8e2692008-05-23 01:52:21 +00009757 if (SrcETy->isSingleValueType())
Owen Andersond672ecb2009-07-03 00:17:18 +00009758 NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009759 }
9760 }
9761
9762
Chris Lattnerf497b022008-01-13 23:50:23 +00009763 // If the memcpy/memmove provides better alignment info than we can
9764 // infer, use it.
9765 SrcAlign = std::max(SrcAlign, CopyAlign);
9766 DstAlign = std::max(DstAlign, CopyAlign);
9767
9768 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9769 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009770 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9771 InsertNewInstBefore(L, *MI);
9772 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9773
9774 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009775 MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009776 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009777}
Chris Lattner3d69f462004-03-12 05:52:32 +00009778
Chris Lattner69ea9d22008-04-30 06:39:11 +00009779Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9780 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009781 if (MI->getAlignment() < Alignment) {
Owen Andersona547b472009-07-09 18:36:20 +00009782 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9783 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009784 return MI;
9785 }
9786
9787 // Extract the length and alignment and fill if they are constant.
9788 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9789 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9790 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9791 return 0;
9792 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009793 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009794
9795 // If the length is zero, this is a no-op
9796 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9797
9798 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9799 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009800 const Type *ITy = Context->getIntegerType(Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009801
9802 Value *Dest = MI->getDest();
Owen Andersond672ecb2009-07-03 00:17:18 +00009803 Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009804
9805 // Alignment 0 is identity for alignment 1 for memset, but not store.
9806 if (Alignment == 0) Alignment = 1;
9807
9808 // Extract the fill value and store.
9809 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersond672ecb2009-07-03 00:17:18 +00009810 InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9811 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009812
9813 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009814 MI->setLength(Context->getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009815 return MI;
9816 }
9817
9818 return 0;
9819}
9820
9821
Chris Lattner8b0ea312006-01-13 20:11:04 +00009822/// visitCallInst - CallInst simplification. This mostly only handles folding
9823/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9824/// the heavy lifting.
9825///
Chris Lattner9fe38862003-06-19 17:00:31 +00009826Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009827 // If the caller function is nounwind, mark the call as nounwind, even if the
9828 // callee isn't.
9829 if (CI.getParent()->getParent()->doesNotThrow() &&
9830 !CI.doesNotThrow()) {
9831 CI.setDoesNotThrow();
9832 return &CI;
9833 }
9834
9835
9836
Chris Lattner8b0ea312006-01-13 20:11:04 +00009837 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9838 if (!II) return visitCallSite(&CI);
9839
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009840 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9841 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009842 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009843 bool Changed = false;
9844
9845 // memmove/cpy/set of zero bytes is a noop.
9846 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9847 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9848
Chris Lattner35b9e482004-10-12 04:52:52 +00009849 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009850 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009851 // Replace the instruction with just byte operations. We would
9852 // transform other cases to loads/stores, but we don't know if
9853 // alignment is sufficient.
9854 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009855 }
9856
Chris Lattner35b9e482004-10-12 04:52:52 +00009857 // If we have a memmove and the source operation is a constant global,
9858 // then the source and dest pointers can't alias, so we can change this
9859 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009860 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009861 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9862 if (GVSrc->isConstant()) {
9863 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009864 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9865 const Type *Tys[1];
9866 Tys[0] = CI.getOperand(3)->getType();
9867 CI.setOperand(0,
9868 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009869 Changed = true;
9870 }
Chris Lattnera935db82008-05-28 05:30:41 +00009871
9872 // memmove(x,x,size) -> noop.
9873 if (MMI->getSource() == MMI->getDest())
9874 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009875 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009876
Chris Lattner95a959d2006-03-06 20:18:44 +00009877 // If we can determine a pointer alignment that is bigger than currently
9878 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009879 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009880 if (Instruction *I = SimplifyMemTransfer(MI))
9881 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009882 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9883 if (Instruction *I = SimplifyMemSet(MSI))
9884 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009885 }
9886
Chris Lattner8b0ea312006-01-13 20:11:04 +00009887 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009888 }
9889
9890 switch (II->getIntrinsicID()) {
9891 default: break;
9892 case Intrinsic::bswap:
9893 // bswap(bswap(x)) -> x
9894 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9895 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9896 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9897 break;
9898 case Intrinsic::ppc_altivec_lvx:
9899 case Intrinsic::ppc_altivec_lvxl:
9900 case Intrinsic::x86_sse_loadu_ps:
9901 case Intrinsic::x86_sse2_loadu_pd:
9902 case Intrinsic::x86_sse2_loadu_dq:
9903 // Turn PPC lvx -> load if the pointer is known aligned.
9904 // Turn X86 loadups -> load if the pointer is known aligned.
9905 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9906 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00009907 Context->getPointerTypeUnqual(II->getType()),
Chris Lattner0521e3c2008-06-18 04:33:20 +00009908 CI);
9909 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009910 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009911 break;
9912 case Intrinsic::ppc_altivec_stvx:
9913 case Intrinsic::ppc_altivec_stvxl:
9914 // Turn stvx -> store if the pointer is known aligned.
9915 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9916 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009917 Context->getPointerTypeUnqual(II->getOperand(1)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009918 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9919 return new StoreInst(II->getOperand(1), Ptr);
9920 }
9921 break;
9922 case Intrinsic::x86_sse_storeu_ps:
9923 case Intrinsic::x86_sse2_storeu_pd:
9924 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009925 // Turn X86 storeu -> store if the pointer is known aligned.
9926 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9927 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009928 Context->getPointerTypeUnqual(II->getOperand(2)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009929 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9930 return new StoreInst(II->getOperand(2), Ptr);
9931 }
9932 break;
9933
9934 case Intrinsic::x86_sse_cvttss2si: {
9935 // These intrinsics only demands the 0th element of its input vector. If
9936 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009937 unsigned VWidth =
9938 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9939 APInt DemandedElts(VWidth, 1);
9940 APInt UndefElts(VWidth, 0);
9941 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009942 UndefElts)) {
9943 II->setOperand(1, V);
9944 return II;
9945 }
9946 break;
9947 }
9948
9949 case Intrinsic::ppc_altivec_vperm:
9950 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9951 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9952 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009953
Chris Lattner0521e3c2008-06-18 04:33:20 +00009954 // Check that all of the elements are integer constants or undefs.
9955 bool AllEltsOk = true;
9956 for (unsigned i = 0; i != 16; ++i) {
9957 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9958 !isa<UndefValue>(Mask->getOperand(i))) {
9959 AllEltsOk = false;
9960 break;
9961 }
9962 }
9963
9964 if (AllEltsOk) {
9965 // Cast the input vectors to byte vectors.
9966 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9967 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00009968 Value *Result = Context->getUndef(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009969
Chris Lattner0521e3c2008-06-18 04:33:20 +00009970 // Only extract each element once.
9971 Value *ExtractedElts[32];
9972 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9973
Chris Lattnere2ed0572006-04-06 19:19:17 +00009974 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009975 if (isa<UndefValue>(Mask->getOperand(i)))
9976 continue;
9977 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9978 Idx &= 31; // Match the hardware behavior.
9979
9980 if (ExtractedElts[Idx] == 0) {
9981 Instruction *Elt =
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009982 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
9983 Context->getConstantInt(Type::Int32Ty, Idx&15, false), "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009984 InsertNewInstBefore(Elt, CI);
9985 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009986 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009987
Chris Lattner0521e3c2008-06-18 04:33:20 +00009988 // Insert this value into the result vector.
9989 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009990 Context->getConstantInt(Type::Int32Ty, i, false),
9991 "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009992 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009993 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009994 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009995 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009996 }
9997 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009998
Chris Lattner0521e3c2008-06-18 04:33:20 +00009999 case Intrinsic::stackrestore: {
10000 // If the save is right next to the restore, remove the restore. This can
10001 // happen when variable allocas are DCE'd.
10002 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10003 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10004 BasicBlock::iterator BI = SS;
10005 if (&*++BI == II)
10006 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +000010007 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010008 }
10009
10010 // Scan down this block to see if there is another stack restore in the
10011 // same block without an intervening call/alloca.
10012 BasicBlock::iterator BI = II;
10013 TerminatorInst *TI = II->getParent()->getTerminator();
10014 bool CannotRemove = false;
10015 for (++BI; &*BI != TI; ++BI) {
10016 if (isa<AllocaInst>(BI)) {
10017 CannotRemove = true;
10018 break;
10019 }
Chris Lattneraa0bf522008-06-25 05:59:28 +000010020 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10021 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10022 // If there is a stackrestore below this one, remove this one.
10023 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10024 return EraseInstFromFunction(CI);
10025 // Otherwise, ignore the intrinsic.
10026 } else {
10027 // If we found a non-intrinsic call, we can't remove the stack
10028 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010029 CannotRemove = true;
10030 break;
10031 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010032 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010033 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010034
10035 // If the stack restore is in a return/unwind block and if there are no
10036 // allocas or calls between the restore and the return, nuke the restore.
10037 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10038 return EraseInstFromFunction(CI);
10039 break;
10040 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010041 }
10042
Chris Lattner8b0ea312006-01-13 20:11:04 +000010043 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010044}
10045
10046// InvokeInst simplification
10047//
10048Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010049 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010050}
10051
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010052/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10053/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010054static bool isSafeToEliminateVarargsCast(const CallSite CS,
10055 const CastInst * const CI,
10056 const TargetData * const TD,
10057 const int ix) {
10058 if (!CI->isLosslessCast())
10059 return false;
10060
10061 // The size of ByVal arguments is derived from the type, so we
10062 // can't change to a type with a different size. If the size were
10063 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010064 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010065 return true;
10066
10067 const Type* SrcTy =
10068 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10069 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10070 if (!SrcTy->isSized() || !DstTy->isSized())
10071 return false;
Duncan Sands777d2302009-05-09 07:06:46 +000010072 if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010073 return false;
10074 return true;
10075}
10076
Chris Lattnera44d8a22003-10-07 22:32:43 +000010077// visitCallSite - Improvements for call and invoke instructions.
10078//
10079Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010080 bool Changed = false;
10081
10082 // If the callee is a constexpr cast of a function, attempt to move the cast
10083 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010084 if (transformConstExprCastCall(CS)) return 0;
10085
Chris Lattner6c266db2003-10-07 22:54:13 +000010086 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010087
Chris Lattner08b22ec2005-05-13 07:09:09 +000010088 if (Function *CalleeF = dyn_cast<Function>(Callee))
10089 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10090 Instruction *OldCall = CS.getInstruction();
10091 // If the call and callee calling conventions don't match, this call must
10092 // be unreachable, as the call is undefined.
Owen Andersond672ecb2009-07-03 00:17:18 +000010093 new StoreInst(Context->getConstantIntTrue(),
10094 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10095 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +000010096 if (!OldCall->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000010097 OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010098 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10099 return EraseInstFromFunction(*OldCall);
10100 return 0;
10101 }
10102
Chris Lattner17be6352004-10-18 02:59:09 +000010103 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10104 // This instruction is not reachable, just remove it. We insert a store to
10105 // undef so that we know that this code is not reachable, despite the fact
10106 // that we can't modify the CFG here.
Owen Andersond672ecb2009-07-03 00:17:18 +000010107 new StoreInst(Context->getConstantIntTrue(),
10108 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +000010109 CS.getInstruction());
10110
10111 if (!CS.getInstruction()->use_empty())
10112 CS.getInstruction()->
Owen Andersond672ecb2009-07-03 00:17:18 +000010113 replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010114
10115 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10116 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010117 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Andersond672ecb2009-07-03 00:17:18 +000010118 Context->getConstantIntTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010119 }
Chris Lattner17be6352004-10-18 02:59:09 +000010120 return EraseInstFromFunction(*CS.getInstruction());
10121 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010122
Duncan Sandscdb6d922007-09-17 10:26:40 +000010123 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10124 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10125 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10126 return transformCallThroughTrampoline(CS);
10127
Chris Lattner6c266db2003-10-07 22:54:13 +000010128 const PointerType *PTy = cast<PointerType>(Callee->getType());
10129 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10130 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010131 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010132 // See if we can optimize any arguments passed through the varargs area of
10133 // the call.
10134 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010135 E = CS.arg_end(); I != E; ++I, ++ix) {
10136 CastInst *CI = dyn_cast<CastInst>(*I);
10137 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10138 *I = CI->getOperand(0);
10139 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010140 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010141 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010142 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010143
Duncan Sandsf0c33542007-12-19 21:13:37 +000010144 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010145 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010146 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010147 Changed = true;
10148 }
10149
Chris Lattner6c266db2003-10-07 22:54:13 +000010150 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010151}
10152
Chris Lattner9fe38862003-06-19 17:00:31 +000010153// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10154// attempt to move the cast to the arguments of the call/invoke.
10155//
10156bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10157 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10158 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010159 if (CE->getOpcode() != Instruction::BitCast ||
10160 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010161 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010162 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010163 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010164 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010165
10166 // Okay, this is a cast from a function to a different type. Unless doing so
10167 // would cause a type conversion of one of our arguments, change this call to
10168 // be a direct call with arguments casted to the appropriate types.
10169 //
10170 const FunctionType *FT = Callee->getFunctionType();
10171 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010172 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010173
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010174 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010175 return false; // TODO: Handle multiple return values.
10176
Chris Lattnerf78616b2004-01-14 06:06:08 +000010177 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010178 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010179 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010180 // Conversion is ok if changing from one pointer type to another or from
10181 // a pointer to an integer of the same size.
10182 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +000010183 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +000010184 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010185
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010186 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010187 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010188 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010189 return false; // Cannot transform this return value.
10190
Chris Lattner58d74912008-03-12 17:45:29 +000010191 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010192 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010193 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010194 return false; // Attribute not compatible with transformed value.
10195 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010196
Chris Lattnerf78616b2004-01-14 06:06:08 +000010197 // If the callsite is an invoke instruction, and the return value is used by
10198 // a PHI node in a successor, we cannot change the return type of the call
10199 // because there is no place to put the cast instruction (without breaking
10200 // the critical edge). Bail out in this case.
10201 if (!Caller->use_empty())
10202 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10203 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10204 UI != E; ++UI)
10205 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10206 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010207 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010208 return false;
10209 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010210
10211 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10212 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010213
Chris Lattner9fe38862003-06-19 17:00:31 +000010214 CallSite::arg_iterator AI = CS.arg_begin();
10215 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10216 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010217 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010218
10219 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010220 return false; // Cannot transform this parameter value.
10221
Devang Patel19c87462008-09-26 22:53:05 +000010222 if (CallerPAL.getParamAttributes(i + 1)
10223 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010224 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010225
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010226 // Converting from one pointer type to another or between a pointer and an
10227 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010228 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010229 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10230 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010231 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010232 }
10233
10234 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010235 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010236 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010237
Chris Lattner58d74912008-03-12 17:45:29 +000010238 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10239 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010240 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010241 // won't be dropping them. Check that these extra arguments have attributes
10242 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010243 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10244 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010245 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010246 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010247 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010248 return false;
10249 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010250
Chris Lattner9fe38862003-06-19 17:00:31 +000010251 // Okay, we decided that this is a safe thing to do: go ahead and start
10252 // inserting cast instructions as necessary...
10253 std::vector<Value*> Args;
10254 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010255 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010256 attrVec.reserve(NumCommonArgs);
10257
10258 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010259 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010260
10261 // If the return value is not being used, the type may not be compatible
10262 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010263 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010264
10265 // Add the new return attributes.
10266 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010267 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010268
10269 AI = CS.arg_begin();
10270 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10271 const Type *ParamTy = FT->getParamType(i);
10272 if ((*AI)->getType() == ParamTy) {
10273 Args.push_back(*AI);
10274 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010275 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010276 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010277 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010278 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010279 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010280
10281 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010282 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010283 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010284 }
10285
10286 // If the function takes more arguments than the call was taking, add them
10287 // now...
10288 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000010289 Args.push_back(Context->getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010290
10291 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010292 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010293 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +000010294 cerr << "WARNING: While resolving call to function '"
10295 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010296 } else {
10297 // Add all of the arguments in their promoted form to the arg list...
10298 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10299 const Type *PTy = getPromotedType((*AI)->getType());
10300 if (PTy != (*AI)->getType()) {
10301 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010302 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10303 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010304 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010305 InsertNewInstBefore(Cast, *Caller);
10306 Args.push_back(Cast);
10307 } else {
10308 Args.push_back(*AI);
10309 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010310
Duncan Sandse1e520f2008-01-13 08:02:44 +000010311 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010312 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010313 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010314 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010315 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010316 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010317
Devang Patel19c87462008-09-26 22:53:05 +000010318 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10319 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10320
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010321 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +000010322 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010323
Devang Patel05988662008-09-25 21:00:45 +000010324 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010325
Chris Lattner9fe38862003-06-19 17:00:31 +000010326 Instruction *NC;
10327 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010328 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010329 Args.begin(), Args.end(),
10330 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010331 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010332 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010333 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010334 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10335 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010336 CallInst *CI = cast<CallInst>(Caller);
10337 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010338 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010339 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010340 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010341 }
10342
Chris Lattner6934a042007-02-11 01:23:03 +000010343 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010344 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010345 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010346 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010347 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010348 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010349 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010350
10351 // If this is an invoke instruction, we should insert it after the first
10352 // non-phi, instruction in the normal successor block.
10353 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010354 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010355 InsertNewInstBefore(NC, *I);
10356 } else {
10357 // Otherwise, it's a call, just insert cast right after the call instr
10358 InsertNewInstBefore(NC, *Caller);
10359 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010360 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010361 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000010362 NV = Context->getUndef(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010363 }
10364 }
10365
10366 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10367 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010368 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010369 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010370 return true;
10371}
10372
Duncan Sandscdb6d922007-09-17 10:26:40 +000010373// transformCallThroughTrampoline - Turn a call to a function created by the
10374// init_trampoline intrinsic into a direct call to the underlying function.
10375//
10376Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10377 Value *Callee = CS.getCalledValue();
10378 const PointerType *PTy = cast<PointerType>(Callee->getType());
10379 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010380 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010381
10382 // If the call already has the 'nest' attribute somewhere then give up -
10383 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010384 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010385 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010386
10387 IntrinsicInst *Tramp =
10388 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10389
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010390 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010391 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10392 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10393
Devang Patel05988662008-09-25 21:00:45 +000010394 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010395 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010396 unsigned NestIdx = 1;
10397 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010398 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010399
10400 // Look for a parameter marked with the 'nest' attribute.
10401 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10402 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010403 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010404 // Record the parameter type and any other attributes.
10405 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010406 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010407 break;
10408 }
10409
10410 if (NestTy) {
10411 Instruction *Caller = CS.getInstruction();
10412 std::vector<Value*> NewArgs;
10413 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10414
Devang Patel05988662008-09-25 21:00:45 +000010415 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010416 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010417
Duncan Sandscdb6d922007-09-17 10:26:40 +000010418 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010419 // mean appending it. Likewise for attributes.
10420
Devang Patel19c87462008-09-26 22:53:05 +000010421 // Add any result attributes.
10422 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010423 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010424
Duncan Sandscdb6d922007-09-17 10:26:40 +000010425 {
10426 unsigned Idx = 1;
10427 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10428 do {
10429 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010430 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010431 Value *NestVal = Tramp->getOperand(3);
10432 if (NestVal->getType() != NestTy)
10433 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10434 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010435 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010436 }
10437
10438 if (I == E)
10439 break;
10440
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010441 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010442 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010443 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010444 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010445 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010446
10447 ++Idx, ++I;
10448 } while (1);
10449 }
10450
Devang Patel19c87462008-09-26 22:53:05 +000010451 // Add any function attributes.
10452 if (Attributes Attr = Attrs.getFnAttributes())
10453 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10454
Duncan Sandscdb6d922007-09-17 10:26:40 +000010455 // The trampoline may have been bitcast to a bogus type (FTy).
10456 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010457 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010458
Duncan Sandscdb6d922007-09-17 10:26:40 +000010459 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010460 NewTypes.reserve(FTy->getNumParams()+1);
10461
Duncan Sandscdb6d922007-09-17 10:26:40 +000010462 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010463 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010464 {
10465 unsigned Idx = 1;
10466 FunctionType::param_iterator I = FTy->param_begin(),
10467 E = FTy->param_end();
10468
10469 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010470 if (Idx == NestIdx)
10471 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010472 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010473
10474 if (I == E)
10475 break;
10476
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010477 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010478 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010479
10480 ++Idx, ++I;
10481 } while (1);
10482 }
10483
10484 // Replace the trampoline call with a direct call. Let the generic
10485 // code sort out any function type mismatches.
10486 FunctionType *NewFTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000010487 Context->getFunctionType(FTy->getReturnType(), NewTypes,
10488 FTy->isVarArg());
10489 Constant *NewCallee =
10490 NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10491 NestF : Context->getConstantExprBitCast(NestF,
10492 Context->getPointerTypeUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +000010493 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010494
10495 Instruction *NewCaller;
10496 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010497 NewCaller = InvokeInst::Create(NewCallee,
10498 II->getNormalDest(), II->getUnwindDest(),
10499 NewArgs.begin(), NewArgs.end(),
10500 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010501 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010502 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010503 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010504 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10505 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010506 if (cast<CallInst>(Caller)->isTailCall())
10507 cast<CallInst>(NewCaller)->setTailCall();
10508 cast<CallInst>(NewCaller)->
10509 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010510 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010511 }
10512 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10513 Caller->replaceAllUsesWith(NewCaller);
10514 Caller->eraseFromParent();
10515 RemoveFromWorkList(Caller);
10516 return 0;
10517 }
10518 }
10519
10520 // Replace the trampoline call with a direct call. Since there is no 'nest'
10521 // parameter, there is no need to adjust the argument list. Let the generic
10522 // code sort out any function type mismatches.
10523 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010524 NestF->getType() == PTy ? NestF :
10525 Context->getConstantExprBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010526 CS.setCalledFunction(NewCallee);
10527 return CS.getInstruction();
10528}
10529
Chris Lattner7da52b22006-11-01 04:51:18 +000010530/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10531/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10532/// and a single binop.
10533Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10534 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010535 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010536 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010537 Value *LHSVal = FirstInst->getOperand(0);
10538 Value *RHSVal = FirstInst->getOperand(1);
10539
10540 const Type *LHSType = LHSVal->getType();
10541 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010542
10543 // Scan to see if all operands are the same opcode, all have one use, and all
10544 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010545 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010546 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010547 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010548 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010549 // types or GEP's with different index types.
10550 I->getOperand(0)->getType() != LHSType ||
10551 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010552 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010553
10554 // If they are CmpInst instructions, check their predicates
10555 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10556 if (cast<CmpInst>(I)->getPredicate() !=
10557 cast<CmpInst>(FirstInst)->getPredicate())
10558 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010559
10560 // Keep track of which operand needs a phi node.
10561 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10562 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010563 }
10564
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010565 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010566
Chris Lattner7da52b22006-11-01 04:51:18 +000010567 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010568 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010569 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010570 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010571 NewLHS = PHINode::Create(LHSType,
10572 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010573 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10574 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010575 InsertNewInstBefore(NewLHS, PN);
10576 LHSVal = NewLHS;
10577 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010578
10579 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010580 NewRHS = PHINode::Create(RHSType,
10581 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010582 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10583 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010584 InsertNewInstBefore(NewRHS, PN);
10585 RHSVal = NewRHS;
10586 }
10587
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010588 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010589 if (NewLHS || NewRHS) {
10590 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10591 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10592 if (NewLHS) {
10593 Value *NewInLHS = InInst->getOperand(0);
10594 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10595 }
10596 if (NewRHS) {
10597 Value *NewInRHS = InInst->getOperand(1);
10598 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10599 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010600 }
10601 }
10602
Chris Lattner7da52b22006-11-01 04:51:18 +000010603 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010604 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010605 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Owen Anderson333c4002009-07-09 23:48:35 +000010606 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10607 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010608}
10609
Chris Lattner05f18922008-12-01 02:34:36 +000010610Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10611 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10612
10613 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10614 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010615 // This is true if all GEP bases are allocas and if all indices into them are
10616 // constants.
10617 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010618
10619 // Scan to see if all operands are the same opcode, all have one use, and all
10620 // kill their operands (i.e. the operands have one use).
10621 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10622 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10623 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10624 GEP->getNumOperands() != FirstInst->getNumOperands())
10625 return 0;
10626
Chris Lattner36d3e322009-02-21 00:46:50 +000010627 // Keep track of whether or not all GEPs are of alloca pointers.
10628 if (AllBasePointersAreAllocas &&
10629 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10630 !GEP->hasAllConstantIndices()))
10631 AllBasePointersAreAllocas = false;
10632
Chris Lattner05f18922008-12-01 02:34:36 +000010633 // Compare the operand lists.
10634 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10635 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10636 continue;
10637
10638 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10639 // if one of the PHIs has a constant for the index. The index may be
10640 // substantially cheaper to compute for the constants, so making it a
10641 // variable index could pessimize the path. This also handles the case
10642 // for struct indices, which must always be constant.
10643 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10644 isa<ConstantInt>(GEP->getOperand(op)))
10645 return 0;
10646
10647 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10648 return 0;
10649 FixedOperands[op] = 0; // Needs a PHI.
10650 }
10651 }
10652
Chris Lattner36d3e322009-02-21 00:46:50 +000010653 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010654 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010655 // offset calculation, but all the predecessors will have to materialize the
10656 // stack address into a register anyway. We'd actually rather *clone* the
10657 // load up into the predecessors so that we have a load of a gep of an alloca,
10658 // which can usually all be folded into the load.
10659 if (AllBasePointersAreAllocas)
10660 return 0;
10661
Chris Lattner05f18922008-12-01 02:34:36 +000010662 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10663 // that is variable.
10664 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10665
10666 bool HasAnyPHIs = false;
10667 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10668 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10669 Value *FirstOp = FirstInst->getOperand(i);
10670 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10671 FirstOp->getName()+".pn");
10672 InsertNewInstBefore(NewPN, PN);
10673
10674 NewPN->reserveOperandSpace(e);
10675 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10676 OperandPhis[i] = NewPN;
10677 FixedOperands[i] = NewPN;
10678 HasAnyPHIs = true;
10679 }
10680
10681
10682 // Add all operands to the new PHIs.
10683 if (HasAnyPHIs) {
10684 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10685 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10686 BasicBlock *InBB = PN.getIncomingBlock(i);
10687
10688 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10689 if (PHINode *OpPhi = OperandPhis[op])
10690 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10691 }
10692 }
10693
10694 Value *Base = FixedOperands[0];
10695 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10696 FixedOperands.end());
10697}
10698
10699
Chris Lattner21550882009-02-23 05:56:17 +000010700/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10701/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010702/// obvious the value of the load is not changed from the point of the load to
10703/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010704///
10705/// Finally, it is safe, but not profitable, to sink a load targetting a
10706/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10707/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010708static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010709 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10710
10711 for (++BBI; BBI != E; ++BBI)
10712 if (BBI->mayWriteToMemory())
10713 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010714
10715 // Check for non-address taken alloca. If not address-taken already, it isn't
10716 // profitable to do this xform.
10717 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10718 bool isAddressTaken = false;
10719 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10720 UI != E; ++UI) {
10721 if (isa<LoadInst>(UI)) continue;
10722 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10723 // If storing TO the alloca, then the address isn't taken.
10724 if (SI->getOperand(1) == AI) continue;
10725 }
10726 isAddressTaken = true;
10727 break;
10728 }
10729
Chris Lattner36d3e322009-02-21 00:46:50 +000010730 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010731 return false;
10732 }
10733
Chris Lattner36d3e322009-02-21 00:46:50 +000010734 // If this load is a load from a GEP with a constant offset from an alloca,
10735 // then we don't want to sink it. In its present form, it will be
10736 // load [constant stack offset]. Sinking it will cause us to have to
10737 // materialize the stack addresses in each predecessor in a register only to
10738 // do a shared load from register in the successor.
10739 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10740 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10741 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10742 return false;
10743
Chris Lattner76c73142006-11-01 07:13:54 +000010744 return true;
10745}
10746
Chris Lattner9fe38862003-06-19 17:00:31 +000010747
Chris Lattnerbac32862004-11-14 19:13:23 +000010748// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10749// operator and they all are only used by the PHI, PHI together their
10750// inputs, and do the operation once, to the result of the PHI.
10751Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10752 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10753
10754 // Scan the instruction, looking for input operations that can be folded away.
10755 // If all input operands to the phi are the same instruction (e.g. a cast from
10756 // the same type or "+42") we can pull the operation through the PHI, reducing
10757 // code size and simplifying code.
10758 Constant *ConstantOp = 0;
10759 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010760 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010761 if (isa<CastInst>(FirstInst)) {
10762 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010763 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010764 // Can fold binop, compare or shift here if the RHS is a constant,
10765 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010766 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010767 if (ConstantOp == 0)
10768 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010769 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10770 isVolatile = LI->isVolatile();
10771 // We can't sink the load if the loaded value could be modified between the
10772 // load and the PHI.
10773 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010774 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010775 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010776
10777 // If the PHI is of volatile loads and the load block has multiple
10778 // successors, sinking it would remove a load of the volatile value from
10779 // the path through the other successor.
10780 if (isVolatile &&
10781 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10782 return 0;
10783
Chris Lattner9c080502006-11-01 07:43:41 +000010784 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010785 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010786 } else {
10787 return 0; // Cannot fold this operation.
10788 }
10789
10790 // Check to see if all arguments are the same operation.
10791 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10792 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10793 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010794 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010795 return 0;
10796 if (CastSrcTy) {
10797 if (I->getOperand(0)->getType() != CastSrcTy)
10798 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010799 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010800 // We can't sink the load if the loaded value could be modified between
10801 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010802 if (LI->isVolatile() != isVolatile ||
10803 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010804 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010805 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010806
Chris Lattner71042962008-07-08 17:18:32 +000010807 // If the PHI is of volatile loads and the load block has multiple
10808 // successors, sinking it would remove a load of the volatile value from
10809 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010810 if (isVolatile &&
10811 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10812 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010813
Chris Lattnerbac32862004-11-14 19:13:23 +000010814 } else if (I->getOperand(1) != ConstantOp) {
10815 return 0;
10816 }
10817 }
10818
10819 // Okay, they are all the same operation. Create a new PHI node of the
10820 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010821 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10822 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010823 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010824
10825 Value *InVal = FirstInst->getOperand(0);
10826 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010827
10828 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010829 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10830 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10831 if (NewInVal != InVal)
10832 InVal = 0;
10833 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10834 }
10835
10836 Value *PhiVal;
10837 if (InVal) {
10838 // The new PHI unions all of the same values together. This is really
10839 // common, so we handle it intelligently here for compile-time speed.
10840 PhiVal = InVal;
10841 delete NewPN;
10842 } else {
10843 InsertNewInstBefore(NewPN, PN);
10844 PhiVal = NewPN;
10845 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010846
Chris Lattnerbac32862004-11-14 19:13:23 +000010847 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010848 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010849 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010850 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010851 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010852 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Owen Anderson333c4002009-07-09 23:48:35 +000010853 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010854 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010855 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10856
10857 // If this was a volatile load that we are merging, make sure to loop through
10858 // and mark all the input loads as non-volatile. If we don't do this, we will
10859 // insert a new volatile load and the old ones will not be deletable.
10860 if (isVolatile)
10861 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10862 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10863
10864 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010865}
Chris Lattnera1be5662002-05-02 17:06:02 +000010866
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010867/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10868/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010869static bool DeadPHICycle(PHINode *PN,
10870 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010871 if (PN->use_empty()) return true;
10872 if (!PN->hasOneUse()) return false;
10873
10874 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010875 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010876 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010877
10878 // Don't scan crazily complex things.
10879 if (PotentiallyDeadPHIs.size() == 16)
10880 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010881
10882 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10883 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010884
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010885 return false;
10886}
10887
Chris Lattnercf5008a2007-11-06 21:52:06 +000010888/// PHIsEqualValue - Return true if this phi node is always equal to
10889/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10890/// z = some value; x = phi (y, z); y = phi (x, z)
10891static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10892 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10893 // See if we already saw this PHI node.
10894 if (!ValueEqualPHIs.insert(PN))
10895 return true;
10896
10897 // Don't scan crazily complex things.
10898 if (ValueEqualPHIs.size() == 16)
10899 return false;
10900
10901 // Scan the operands to see if they are either phi nodes or are equal to
10902 // the value.
10903 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10904 Value *Op = PN->getIncomingValue(i);
10905 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10906 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10907 return false;
10908 } else if (Op != NonPhiInVal)
10909 return false;
10910 }
10911
10912 return true;
10913}
10914
10915
Chris Lattner473945d2002-05-06 18:06:38 +000010916// PHINode simplification
10917//
Chris Lattner7e708292002-06-25 16:13:24 +000010918Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010919 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010920 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010921
Owen Anderson7e057142006-07-10 22:03:18 +000010922 if (Value *V = PN.hasConstantValue())
10923 return ReplaceInstUsesWith(PN, V);
10924
Owen Anderson7e057142006-07-10 22:03:18 +000010925 // If all PHI operands are the same operation, pull them through the PHI,
10926 // reducing code size.
10927 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010928 isa<Instruction>(PN.getIncomingValue(1)) &&
10929 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10930 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10931 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10932 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010933 PN.getIncomingValue(0)->hasOneUse())
10934 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10935 return Result;
10936
10937 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10938 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10939 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010940 if (PN.hasOneUse()) {
10941 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10942 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010943 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010944 PotentiallyDeadPHIs.insert(&PN);
10945 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersond672ecb2009-07-03 00:17:18 +000010946 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010947 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010948
10949 // If this phi has a single use, and if that use just computes a value for
10950 // the next iteration of a loop, delete the phi. This occurs with unused
10951 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10952 // common case here is good because the only other things that catch this
10953 // are induction variable analysis (sometimes) and ADCE, which is only run
10954 // late.
10955 if (PHIUser->hasOneUse() &&
10956 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10957 PHIUser->use_back() == &PN) {
Owen Andersond672ecb2009-07-03 00:17:18 +000010958 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010959 }
10960 }
Owen Anderson7e057142006-07-10 22:03:18 +000010961
Chris Lattnercf5008a2007-11-06 21:52:06 +000010962 // We sometimes end up with phi cycles that non-obviously end up being the
10963 // same value, for example:
10964 // z = some value; x = phi (y, z); y = phi (x, z)
10965 // where the phi nodes don't necessarily need to be in the same block. Do a
10966 // quick check to see if the PHI node only contains a single non-phi value, if
10967 // so, scan to see if the phi cycle is actually equal to that value.
10968 {
10969 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10970 // Scan for the first non-phi operand.
10971 while (InValNo != NumOperandVals &&
10972 isa<PHINode>(PN.getIncomingValue(InValNo)))
10973 ++InValNo;
10974
10975 if (InValNo != NumOperandVals) {
10976 Value *NonPhiInVal = PN.getOperand(InValNo);
10977
10978 // Scan the rest of the operands to see if there are any conflicts, if so
10979 // there is no need to recursively scan other phis.
10980 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10981 Value *OpVal = PN.getIncomingValue(InValNo);
10982 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10983 break;
10984 }
10985
10986 // If we scanned over all operands, then we have one unique value plus
10987 // phi values. Scan PHI nodes to see if they all merge in each other or
10988 // the value.
10989 if (InValNo == NumOperandVals) {
10990 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10991 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10992 return ReplaceInstUsesWith(PN, NonPhiInVal);
10993 }
10994 }
10995 }
Chris Lattner60921c92003-12-19 05:58:40 +000010996 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010997}
10998
Reid Spencer17212df2006-12-12 09:18:51 +000010999static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
11000 Instruction *InsertPoint,
11001 InstCombiner *IC) {
Dan Gohman6de29f82009-06-15 22:12:54 +000011002 unsigned PtrSize = DTy->getScalarSizeInBits();
11003 unsigned VTySize = V->getType()->getScalarSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000011004 // We must cast correctly to the pointer type. Ensure that we
11005 // sign extend the integer value if it is smaller as this is
11006 // used for address computation.
11007 Instruction::CastOps opcode =
11008 (VTySize < PtrSize ? Instruction::SExt :
11009 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
11010 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000011011}
11012
Chris Lattnera1be5662002-05-02 17:06:02 +000011013
Chris Lattner7e708292002-06-25 16:13:24 +000011014Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000011015 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000011016 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000011017 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011018 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000011019 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011020
Chris Lattnere87597f2004-10-16 18:11:37 +000011021 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000011022 return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011023
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011024 bool HasZeroPointerIndex = false;
11025 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11026 HasZeroPointerIndex = C->isNullValue();
11027
11028 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011029 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011030
Chris Lattner28977af2004-04-05 01:30:19 +000011031 // Eliminate unneeded casts for indices.
11032 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011033
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011034 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011035 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11036 i != e; ++i, ++GTI) {
Sanjiv Gupta7787d4a2009-04-24 02:37:54 +000011037 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000011038 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011039 if (CI->getOpcode() == Instruction::ZExt ||
11040 CI->getOpcode() == Instruction::SExt) {
11041 const Type *SrcTy = CI->getOperand(0)->getType();
11042 // We can eliminate a cast from i32 to i64 iff the target
11043 // is a 32-bit pointer target.
Dan Gohman6de29f82009-06-15 22:12:54 +000011044 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011045 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000011046 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000011047 }
11048 }
11049 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011050 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000011051 // to what we need. If narrower, sign-extend it to what we need.
11052 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011053 // insert it. This explicit cast can make subsequent optimizations more
11054 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000011055 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011056 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000011057 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011058 *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000011059 MadeChange = true;
11060 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000011061 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11062 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011063 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011064 MadeChange = true;
11065 }
Dan Gohman4f833d42008-09-11 23:06:38 +000011066 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11067 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011068 *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
Dan Gohman4f833d42008-09-11 23:06:38 +000011069 MadeChange = true;
11070 } else {
11071 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11072 GEP);
11073 *i = Op;
11074 MadeChange = true;
11075 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011076 }
Chris Lattner28977af2004-04-05 01:30:19 +000011077 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011078 }
Chris Lattner28977af2004-04-05 01:30:19 +000011079 if (MadeChange) return &GEP;
11080
Chris Lattner90ac28c2002-08-02 19:29:35 +000011081 // Combine Indices - If the source pointer to this getelementptr instruction
11082 // is a getelementptr instruction, combine the indices of the two
11083 // getelementptr instructions into a single instruction.
11084 //
Chris Lattner72588fc2007-02-15 22:48:32 +000011085 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000011086 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000011087 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000011088
11089 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000011090 // Note that if our source is a gep chain itself that we wait for that
11091 // chain to be resolved before we perform this transformation. This
11092 // avoids us creating a TON of code in some cases.
11093 //
11094 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11095 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11096 return 0; // Wait until our source is folded to completion.
11097
Chris Lattner72588fc2007-02-15 22:48:32 +000011098 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011099
11100 // Find out whether the last index in the source GEP is a sequential idx.
11101 bool EndsWithSequential = false;
11102 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11103 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011104 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011105
Chris Lattner90ac28c2002-08-02 19:29:35 +000011106 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011107 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011108 // Replace: gep (gep %P, long B), long A, ...
11109 // With: T = long A+B; gep %P, T, ...
11110 //
Chris Lattner620ce142004-05-07 22:09:22 +000011111 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011112 if (SO1 == Context->getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011113 Sum = GO1;
Owen Andersond672ecb2009-07-03 00:17:18 +000011114 } else if (GO1 == Context->getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011115 Sum = SO1;
11116 } else {
11117 // If they aren't the same type, convert both to an integer of the
11118 // target's pointer size.
11119 if (SO1->getType() != GO1->getType()) {
11120 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011121 SO1 =
11122 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011123 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011124 GO1 =
11125 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011126 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000011127 unsigned PS = TD->getPointerSizeInBits();
11128 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011129 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011130 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011131
Duncan Sands514ab342007-11-01 20:53:16 +000011132 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011133 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011134 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011135 } else {
11136 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000011137 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11138 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011139 }
11140 }
11141 }
Chris Lattner620ce142004-05-07 22:09:22 +000011142 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Andersond672ecb2009-07-03 00:17:18 +000011143 Sum = Context->getConstantExprAdd(cast<Constant>(SO1),
11144 cast<Constant>(GO1));
Chris Lattner620ce142004-05-07 22:09:22 +000011145 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011146 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011147 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011148 }
Chris Lattner28977af2004-04-05 01:30:19 +000011149 }
Chris Lattner620ce142004-05-07 22:09:22 +000011150
11151 // Recycle the GEP we already have if possible.
11152 if (SrcGEPOperands.size() == 2) {
11153 GEP.setOperand(0, SrcGEPOperands[0]);
11154 GEP.setOperand(1, Sum);
11155 return &GEP;
11156 } else {
11157 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11158 SrcGEPOperands.end()-1);
11159 Indices.push_back(Sum);
11160 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11161 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011162 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011163 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000011164 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011165 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000011166 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11167 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011168 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11169 }
11170
11171 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000011172 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11173 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000011174
Chris Lattner620ce142004-05-07 22:09:22 +000011175 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000011176 // GEP of global variable. If all of the indices for this GEP are
11177 // constants, we can promote this to a constexpr instead of an instruction.
11178
11179 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000011180 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000011181 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11182 for (; I != E && isa<Constant>(*I); ++I)
11183 Indices.push_back(cast<Constant>(*I));
11184
11185 if (I == E) { // If they are all constants...
Owen Andersond672ecb2009-07-03 00:17:18 +000011186 Constant *CE = Context->getConstantExprGetElementPtr(GV,
Chris Lattner55eb1c42007-01-31 04:40:53 +000011187 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000011188
11189 // Replace all uses of the GEP with the new constexpr...
11190 return ReplaceInstUsesWith(GEP, CE);
11191 }
Reid Spencer3da59db2006-11-27 01:05:10 +000011192 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000011193 if (!isa<PointerType>(X->getType())) {
11194 // Not interesting. Source pointer must be a cast from pointer.
11195 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011196 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11197 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011198 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011199 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11200 // into : GEP i8* X, ...
11201 //
Chris Lattnereed48272005-09-13 00:40:14 +000011202 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011203 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11204 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011205 if (const ArrayType *CATy =
11206 dyn_cast<ArrayType>(CPTy->getElementType())) {
11207 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11208 if (CATy->getElementType() == XTy->getElementType()) {
11209 // -> GEP i8* X, ...
11210 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11211 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11212 GEP.getName());
11213 } else if (const ArrayType *XATy =
11214 dyn_cast<ArrayType>(XTy->getElementType())) {
11215 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011216 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011217 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011218 // At this point, we know that the cast source type is a pointer
11219 // to an array of the same type as the destination pointer
11220 // array. Because the array type is never stepped over (there
11221 // is a leading zero) we can fold the cast into this GEP.
11222 GEP.setOperand(0, X);
11223 return &GEP;
11224 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011225 }
11226 }
Chris Lattnereed48272005-09-13 00:40:14 +000011227 } else if (GEP.getNumOperands() == 2) {
11228 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011229 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11230 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011231 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11232 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11233 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011234 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11235 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011236 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011237 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011238 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000011239 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000011240 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011241 // V and GEP are both pointer types --> BitCast
11242 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011243 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011244
11245 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011246 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011247 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011248 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011249
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011250 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011251 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011252 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011253
11254 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11255 // allow either a mul, shift, or constant here.
11256 Value *NewIdx = 0;
11257 ConstantInt *Scale = 0;
11258 if (ArrayEltSize == 1) {
11259 NewIdx = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011260 Scale =
11261 Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011262 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011263 NewIdx = Context->getConstantInt(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011264 Scale = CI;
11265 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11266 if (Inst->getOpcode() == Instruction::Shl &&
11267 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011268 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11269 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersond672ecb2009-07-03 00:17:18 +000011270 Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011271 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011272 NewIdx = Inst->getOperand(0);
11273 } else if (Inst->getOpcode() == Instruction::Mul &&
11274 isa<ConstantInt>(Inst->getOperand(1))) {
11275 Scale = cast<ConstantInt>(Inst->getOperand(1));
11276 NewIdx = Inst->getOperand(0);
11277 }
11278 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011279
Chris Lattner7835cdd2005-09-13 18:36:04 +000011280 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011281 // out, perform the transformation. Note, we don't know whether Scale is
11282 // signed or not. We'll use unsigned version of division/modulo
11283 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011284 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011285 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011286 Scale = Context->getConstantInt(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011287 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011288 if (Scale->getZExtValue() != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011289 Constant *C =
11290 Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011291 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011292 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011293 NewIdx = InsertNewInstBefore(Sc, GEP);
11294 }
11295
11296 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011297 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011298 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011299 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011300 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011301 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011302 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11303 // The NewGEP must be pointer typed, so must the old one -> BitCast
11304 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011305 }
11306 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011307 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011308 }
Chris Lattner58407792009-01-09 04:53:57 +000011309
Chris Lattner46cd5a12009-01-09 05:44:56 +000011310 /// See if we can simplify:
11311 /// X = bitcast A to B*
11312 /// Y = gep X, <...constant indices...>
11313 /// into a gep of the original struct. This is important for SROA and alias
11314 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011315 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011316 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11317 // Determine how much the GEP moves the pointer. We are guaranteed to get
11318 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011319 ConstantInt *OffsetV =
11320 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011321 int64_t Offset = OffsetV->getSExtValue();
11322
11323 // If this GEP instruction doesn't move the pointer, just replace the GEP
11324 // with a bitcast of the real input to the dest type.
11325 if (Offset == 0) {
11326 // If the bitcast is of an allocation, and the allocation will be
11327 // converted to match the type of the cast, don't touch this.
11328 if (isa<AllocationInst>(BCI->getOperand(0))) {
11329 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11330 if (Instruction *I = visitBitCast(*BCI)) {
11331 if (I != BCI) {
11332 I->takeName(BCI);
11333 BCI->getParent()->getInstList().insert(BCI, I);
11334 ReplaceInstUsesWith(*BCI, I);
11335 }
11336 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011337 }
Chris Lattner58407792009-01-09 04:53:57 +000011338 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011339 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011340 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011341
11342 // Otherwise, if the offset is non-zero, we need to find out if there is a
11343 // field at Offset in 'A's type. If so, we can pull the cast through the
11344 // GEP.
11345 SmallVector<Value*, 8> NewIndices;
11346 const Type *InTy =
11347 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011348 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011349 Instruction *NGEP =
11350 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11351 NewIndices.end());
11352 if (NGEP->getType() == GEP.getType()) return NGEP;
11353 InsertNewInstBefore(NGEP, GEP);
11354 NGEP->takeName(&GEP);
11355 return new BitCastInst(NGEP, GEP.getType());
11356 }
Chris Lattner58407792009-01-09 04:53:57 +000011357 }
11358 }
11359
Chris Lattner8a2a3112001-12-14 16:52:21 +000011360 return 0;
11361}
11362
Chris Lattner0864acf2002-11-04 16:18:53 +000011363Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11364 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011365 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011366 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11367 const Type *NewTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000011368 Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011369 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011370
11371 // Create and insert the replacement instruction...
11372 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +000011373 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011374 else {
11375 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Owen Anderson50dead02009-07-15 23:53:25 +000011376 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011377 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011378
11379 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011380
Chris Lattner0864acf2002-11-04 16:18:53 +000011381 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011382 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011383 //
11384 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011385 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011386
11387 // Now that I is pointing to the first non-allocation-inst in the block,
11388 // insert our getelementptr instruction...
11389 //
Owen Andersond672ecb2009-07-03 00:17:18 +000011390 Value *NullIdx = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011391 Value *Idx[2];
11392 Idx[0] = NullIdx;
11393 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011394 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11395 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011396
11397 // Now make everything use the getelementptr instead of the original
11398 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011399 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011400 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011401 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011402 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011403 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011404
Dan Gohman6893cd72009-01-13 20:18:38 +000011405 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11406 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011407 // Note that we only do this for alloca's, because malloc should allocate
11408 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011409 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersond672ecb2009-07-03 00:17:18 +000011410 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011411
11412 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11413 if (AI.getAlignment() == 0)
11414 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11415 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011416
Chris Lattner0864acf2002-11-04 16:18:53 +000011417 return 0;
11418}
11419
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011420Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11421 Value *Op = FI.getOperand(0);
11422
Chris Lattner17be6352004-10-18 02:59:09 +000011423 // free undef -> unreachable.
11424 if (isa<UndefValue>(Op)) {
11425 // Insert a new store to null because we cannot modify the CFG here.
Owen Andersond672ecb2009-07-03 00:17:18 +000011426 new StoreInst(Context->getConstantIntTrue(),
11427 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011428 return EraseInstFromFunction(FI);
11429 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011430
Chris Lattner6160e852004-02-28 04:57:37 +000011431 // If we have 'free null' delete the instruction. This can happen in stl code
11432 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011433 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011434 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011435
11436 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11437 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11438 FI.setOperand(0, CI->getOperand(0));
11439 return &FI;
11440 }
11441
11442 // Change free (gep X, 0,0,0,0) into free(X)
11443 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11444 if (GEPI->hasAllZeroIndices()) {
11445 AddToWorkList(GEPI);
11446 FI.setOperand(0, GEPI->getOperand(0));
11447 return &FI;
11448 }
11449 }
11450
11451 // Change free(malloc) into nothing, if the malloc has a single use.
11452 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11453 if (MI->hasOneUse()) {
11454 EraseInstFromFunction(FI);
11455 return EraseInstFromFunction(*MI);
11456 }
Chris Lattner6160e852004-02-28 04:57:37 +000011457
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011458 return 0;
11459}
11460
11461
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011462/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011463static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011464 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011465 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011466 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011467 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011468
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011469 if (TD) {
11470 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11471 // Instead of loading constant c string, use corresponding integer value
11472 // directly if string length is small enough.
11473 std::string Str;
11474 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11475 unsigned len = Str.length();
11476 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11477 unsigned numBits = Ty->getPrimitiveSizeInBits();
11478 // Replace LI with immediate integer store.
11479 if ((numBits >> 3) == len + 1) {
11480 APInt StrVal(numBits, 0);
11481 APInt SingleChar(numBits, 0);
11482 if (TD->isLittleEndian()) {
11483 for (signed i = len-1; i >= 0; i--) {
11484 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11485 StrVal = (StrVal << 8) | SingleChar;
11486 }
11487 } else {
11488 for (unsigned i = 0; i < len; i++) {
11489 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11490 StrVal = (StrVal << 8) | SingleChar;
11491 }
11492 // Append NULL at the end.
11493 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011494 StrVal = (StrVal << 8) | SingleChar;
11495 }
Owen Andersond672ecb2009-07-03 00:17:18 +000011496 Value *NL = Context->getConstantInt(StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011497 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011498 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011499 }
11500 }
11501 }
11502
Mon P Wang6753f952009-02-07 22:19:29 +000011503 const PointerType *DestTy = cast<PointerType>(CI->getType());
11504 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011505 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011506
11507 // If the address spaces don't match, don't eliminate the cast.
11508 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11509 return 0;
11510
Chris Lattnerb89e0712004-07-13 01:49:43 +000011511 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011512
Reid Spencer42230162007-01-22 05:51:25 +000011513 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011514 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011515 // If the source is an array, the code below will not succeed. Check to
11516 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11517 // constants.
11518 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11519 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11520 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011521 Value *Idxs[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011522 Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11523 CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011524 SrcTy = cast<PointerType>(CastOp->getType());
11525 SrcPTy = SrcTy->getElementType();
11526 }
11527
Reid Spencer42230162007-01-22 05:51:25 +000011528 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011529 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011530 // Do not allow turning this into a load of an integer, which is then
11531 // casted to a pointer, this pessimizes pointer analysis a lot.
11532 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000011533 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11534 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011535
Chris Lattnerf9527852005-01-31 04:50:46 +000011536 // Okay, we are casting from one integer or pointer type to another of
11537 // the same size. Instead of casting the pointer before the load, cast
11538 // the result of the loaded value.
11539 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11540 CI->getName(),
11541 LI.isVolatile()),LI);
11542 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011543 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011544 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011545 }
11546 }
11547 return 0;
11548}
11549
Chris Lattner833b8a42003-06-26 05:06:25 +000011550Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11551 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011552
Dan Gohman9941f742007-07-20 16:34:21 +000011553 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011554 unsigned KnownAlign =
11555 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011556 if (KnownAlign >
11557 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11558 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011559 LI.setAlignment(KnownAlign);
11560
Chris Lattner37366c12005-05-01 04:24:53 +000011561 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011562 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011563 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011564 return Res;
11565
11566 // None of the following transforms are legal for volatile loads.
11567 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011568
Dan Gohman2276a7b2008-10-15 23:19:35 +000011569 // Do really simple store-to-load forwarding and load CSE, to catch cases
11570 // where there are several consequtive memory accesses to the same location,
11571 // separated by a few arithmetic operations.
11572 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011573 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11574 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011575
Christopher Lambb15147e2007-12-29 07:56:53 +000011576 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11577 const Value *GEPI0 = GEPI->getOperand(0);
11578 // TODO: Consider a target hook for valid address spaces for this xform.
11579 if (isa<ConstantPointerNull>(GEPI0) &&
11580 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011581 // Insert a new store to null instruction before the load to indicate
11582 // that this code is not reachable. We do this instead of inserting
11583 // an unreachable instruction directly because we cannot modify the
11584 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011585 new StoreInst(Context->getUndef(LI.getType()),
11586 Context->getNullValue(Op->getType()), &LI);
11587 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011588 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011589 }
Chris Lattner37366c12005-05-01 04:24:53 +000011590
Chris Lattnere87597f2004-10-16 18:11:37 +000011591 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011592 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011593 // TODO: Consider a target hook for valid address spaces for this xform.
11594 if (isa<UndefValue>(C) || (C->isNullValue() &&
11595 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011596 // Insert a new store to null instruction before the load to indicate that
11597 // this code is not reachable. We do this instead of inserting an
11598 // unreachable instruction directly because we cannot modify the CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011599 new StoreInst(Context->getUndef(LI.getType()),
11600 Context->getNullValue(Op->getType()), &LI);
11601 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011602 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011603
Chris Lattnere87597f2004-10-16 18:11:37 +000011604 // Instcombine load (constant global) into the value loaded.
11605 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011606 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011607 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011608
Chris Lattnere87597f2004-10-16 18:11:37 +000011609 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011610 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011611 if (CE->getOpcode() == Instruction::GetElementPtr) {
11612 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011613 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011614 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011615 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
11616 Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011617 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011618 if (CE->getOperand(0)->isNullValue()) {
11619 // Insert a new store to null instruction before the load to indicate
11620 // that this code is not reachable. We do this instead of inserting
11621 // an unreachable instruction directly because we cannot modify the
11622 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011623 new StoreInst(Context->getUndef(LI.getType()),
11624 Context->getNullValue(Op->getType()), &LI);
11625 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011626 }
11627
Reid Spencer3da59db2006-11-27 01:05:10 +000011628 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011629 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011630 return Res;
11631 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011632 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011633 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011634
11635 // If this load comes from anywhere in a constant global, and if the global
11636 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011637 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011638 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011639 if (GV->getInitializer()->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +000011640 return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011641 else if (isa<UndefValue>(GV->getInitializer()))
Owen Andersond672ecb2009-07-03 00:17:18 +000011642 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011643 }
11644 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011645
Chris Lattner37366c12005-05-01 04:24:53 +000011646 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011647 // Change select and PHI nodes to select values instead of addresses: this
11648 // helps alias analysis out a lot, allows many others simplifications, and
11649 // exposes redundancy in the code.
11650 //
11651 // Note that we cannot do the transformation unless we know that the
11652 // introduced loads cannot trap! Something like this is valid as long as
11653 // the condition is always false: load (select bool %C, int* null, int* %G),
11654 // but it would not be valid if we transformed it to load from null
11655 // unconditionally.
11656 //
11657 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11658 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011659 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11660 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011661 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011662 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011663 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011664 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011665 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011666 }
11667
Chris Lattner684fe212004-09-23 15:46:00 +000011668 // load (select (cond, null, P)) -> load P
11669 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11670 if (C->isNullValue()) {
11671 LI.setOperand(0, SI->getOperand(2));
11672 return &LI;
11673 }
11674
11675 // load (select (cond, P, null)) -> load P
11676 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11677 if (C->isNullValue()) {
11678 LI.setOperand(0, SI->getOperand(1));
11679 return &LI;
11680 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011681 }
11682 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011683 return 0;
11684}
11685
Reid Spencer55af2b52007-01-19 21:20:31 +000011686/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011687/// when possible. This makes it generally easy to do alias analysis and/or
11688/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011689static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11690 User *CI = cast<User>(SI.getOperand(1));
11691 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011692 LLVMContext *Context = IC.getContext();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011693
11694 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011695 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11696 if (SrcTy == 0) return 0;
11697
11698 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011699
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011700 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11701 return 0;
11702
Chris Lattner3914f722009-01-24 01:00:13 +000011703 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11704 /// to its first element. This allows us to handle things like:
11705 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11706 /// on 32-bit hosts.
11707 SmallVector<Value*, 4> NewGEPIndices;
11708
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011709 // If the source is an array, the code below will not succeed. Check to
11710 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11711 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011712 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11713 // Index through pointer.
Owen Andersond672ecb2009-07-03 00:17:18 +000011714 Constant *Zero = Context->getNullValue(Type::Int32Ty);
Chris Lattner3914f722009-01-24 01:00:13 +000011715 NewGEPIndices.push_back(Zero);
11716
11717 while (1) {
11718 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011719 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011720 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011721 NewGEPIndices.push_back(Zero);
11722 SrcPTy = STy->getElementType(0);
11723 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11724 NewGEPIndices.push_back(Zero);
11725 SrcPTy = ATy->getElementType();
11726 } else {
11727 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011728 }
Chris Lattner3914f722009-01-24 01:00:13 +000011729 }
11730
Owen Andersond672ecb2009-07-03 00:17:18 +000011731 SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011732 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011733
11734 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11735 return 0;
11736
Chris Lattner71759c42009-01-16 20:12:52 +000011737 // If the pointers point into different address spaces or if they point to
11738 // values with different sizes, we can't do the transformation.
11739 if (SrcTy->getAddressSpace() !=
11740 cast<PointerType>(CI->getType())->getAddressSpace() ||
11741 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011742 IC.getTargetData().getTypeSizeInBits(DestPTy))
11743 return 0;
11744
11745 // Okay, we are casting from one integer or pointer type to another of
11746 // the same size. Instead of casting the pointer before
11747 // the store, cast the value to be stored.
11748 Value *NewCast;
11749 Value *SIOp0 = SI.getOperand(0);
11750 Instruction::CastOps opcode = Instruction::BitCast;
11751 const Type* CastSrcTy = SIOp0->getType();
11752 const Type* CastDstTy = SrcPTy;
11753 if (isa<PointerType>(CastDstTy)) {
11754 if (CastSrcTy->isInteger())
11755 opcode = Instruction::IntToPtr;
11756 } else if (isa<IntegerType>(CastDstTy)) {
11757 if (isa<PointerType>(SIOp0->getType()))
11758 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011759 }
Chris Lattner3914f722009-01-24 01:00:13 +000011760
11761 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11762 // emit a GEP to index into its first field.
11763 if (!NewGEPIndices.empty()) {
11764 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000011765 CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner3914f722009-01-24 01:00:13 +000011766 NewGEPIndices.size());
11767 else
11768 CastOp = IC.InsertNewInstBefore(
11769 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11770 NewGEPIndices.end()), SI);
11771 }
11772
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011773 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Andersond672ecb2009-07-03 00:17:18 +000011774 NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011775 else
11776 NewCast = IC.InsertNewInstBefore(
11777 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11778 SI);
11779 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011780}
11781
Chris Lattner4aebaee2008-11-27 08:56:30 +000011782/// equivalentAddressValues - Test if A and B will obviously have the same
11783/// value. This includes recognizing that %t0 and %t1 will have the same
11784/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011785/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011786/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011787/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011788/// %t2 = load i32* %t1
11789///
11790static bool equivalentAddressValues(Value *A, Value *B) {
11791 // Test if the values are trivially equivalent.
11792 if (A == B) return true;
11793
11794 // Test if the values come form identical arithmetic instructions.
11795 if (isa<BinaryOperator>(A) ||
11796 isa<CastInst>(A) ||
11797 isa<PHINode>(A) ||
11798 isa<GetElementPtrInst>(A))
11799 if (Instruction *BI = dyn_cast<Instruction>(B))
11800 if (cast<Instruction>(A)->isIdenticalTo(BI))
11801 return true;
11802
11803 // Otherwise they may not be equivalent.
11804 return false;
11805}
11806
Dale Johannesen4945c652009-03-03 21:26:39 +000011807// If this instruction has two uses, one of which is a llvm.dbg.declare,
11808// return the llvm.dbg.declare.
11809DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11810 if (!V->hasNUses(2))
11811 return 0;
11812 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11813 UI != E; ++UI) {
11814 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11815 return DI;
11816 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11817 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11818 return DI;
11819 }
11820 }
11821 return 0;
11822}
11823
Chris Lattner2f503e62005-01-31 05:36:43 +000011824Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11825 Value *Val = SI.getOperand(0);
11826 Value *Ptr = SI.getOperand(1);
11827
11828 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011829 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011830 ++NumCombined;
11831 return 0;
11832 }
Chris Lattner836692d2007-01-15 06:51:56 +000011833
11834 // If the RHS is an alloca with a single use, zapify the store, making the
11835 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011836 // If the RHS is an alloca with a two uses, the other one being a
11837 // llvm.dbg.declare, zapify the store and the declare, making the
11838 // alloca dead. We must do this to prevent declare's from affecting
11839 // codegen.
11840 if (!SI.isVolatile()) {
11841 if (Ptr->hasOneUse()) {
11842 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011843 EraseInstFromFunction(SI);
11844 ++NumCombined;
11845 return 0;
11846 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011847 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11848 if (isa<AllocaInst>(GEP->getOperand(0))) {
11849 if (GEP->getOperand(0)->hasOneUse()) {
11850 EraseInstFromFunction(SI);
11851 ++NumCombined;
11852 return 0;
11853 }
11854 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11855 EraseInstFromFunction(*DI);
11856 EraseInstFromFunction(SI);
11857 ++NumCombined;
11858 return 0;
11859 }
11860 }
11861 }
11862 }
11863 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11864 EraseInstFromFunction(*DI);
11865 EraseInstFromFunction(SI);
11866 ++NumCombined;
11867 return 0;
11868 }
Chris Lattner836692d2007-01-15 06:51:56 +000011869 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011870
Dan Gohman9941f742007-07-20 16:34:21 +000011871 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011872 unsigned KnownAlign =
11873 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011874 if (KnownAlign >
11875 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11876 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011877 SI.setAlignment(KnownAlign);
11878
Dale Johannesenacb51a32009-03-03 01:43:03 +000011879 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011880 // stores to the same location, separated by a few arithmetic operations. This
11881 // situation often occurs with bitfield accesses.
11882 BasicBlock::iterator BBI = &SI;
11883 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11884 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011885 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011886 // Don't count debug info directives, lest they affect codegen,
11887 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11888 // It is necessary for correctness to skip those that feed into a
11889 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011890 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011891 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011892 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011893 continue;
11894 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011895
11896 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11897 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011898 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11899 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011900 ++NumDeadStore;
11901 ++BBI;
11902 EraseInstFromFunction(*PrevSI);
11903 continue;
11904 }
11905 break;
11906 }
11907
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011908 // If this is a load, we have to stop. However, if the loaded value is from
11909 // the pointer we're loading and is producing the pointer we're storing,
11910 // then *this* store is dead (X = load P; store X -> P).
11911 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011912 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11913 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011914 EraseInstFromFunction(SI);
11915 ++NumCombined;
11916 return 0;
11917 }
11918 // Otherwise, this is a load from some other location. Stores before it
11919 // may not be dead.
11920 break;
11921 }
11922
Chris Lattner9ca96412006-02-08 03:25:32 +000011923 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011924 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011925 break;
11926 }
11927
11928
11929 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011930
11931 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011932 if (isa<ConstantPointerNull>(Ptr) &&
11933 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011934 if (!isa<UndefValue>(Val)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011935 SI.setOperand(0, Context->getUndef(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011936 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011937 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011938 ++NumCombined;
11939 }
11940 return 0; // Do not modify these!
11941 }
11942
11943 // store undef, Ptr -> noop
11944 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011945 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011946 ++NumCombined;
11947 return 0;
11948 }
11949
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011950 // If the pointer destination is a cast, see if we can fold the cast into the
11951 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011952 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011953 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11954 return Res;
11955 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011956 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011957 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11958 return Res;
11959
Chris Lattner408902b2005-09-12 23:23:25 +000011960
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011961 // If this store is the last instruction in the basic block (possibly
11962 // excepting debug info instructions and the pointer bitcasts that feed
11963 // into them), and if the block ends with an unconditional branch, try
11964 // to move it to the successor block.
11965 BBI = &SI;
11966 do {
11967 ++BBI;
11968 } while (isa<DbgInfoIntrinsic>(BBI) ||
11969 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011970 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011971 if (BI->isUnconditional())
11972 if (SimplifyStoreAtEndOfBlock(SI))
11973 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011974
Chris Lattner2f503e62005-01-31 05:36:43 +000011975 return 0;
11976}
11977
Chris Lattner3284d1f2007-04-15 00:07:55 +000011978/// SimplifyStoreAtEndOfBlock - Turn things like:
11979/// if () { *P = v1; } else { *P = v2 }
11980/// into a phi node with a store in the successor.
11981///
Chris Lattner31755a02007-04-15 01:02:18 +000011982/// Simplify things like:
11983/// *P = v1; if () { *P = v2; }
11984/// into a phi node with a store in the successor.
11985///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011986bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11987 BasicBlock *StoreBB = SI.getParent();
11988
11989 // Check to see if the successor block has exactly two incoming edges. If
11990 // so, see if the other predecessor contains a store to the same location.
11991 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011992 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011993
11994 // Determine whether Dest has exactly two predecessors and, if so, compute
11995 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011996 pred_iterator PI = pred_begin(DestBB);
11997 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011998 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011999 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012000 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000012001 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012002 return false;
12003
12004 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000012005 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000012006 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000012007 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012008 }
Chris Lattner31755a02007-04-15 01:02:18 +000012009 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012010 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000012011
12012 // Bail out if all the relevant blocks aren't distinct (this can happen,
12013 // for example, if SI is in an infinite loop)
12014 if (StoreBB == DestBB || OtherBB == DestBB)
12015 return false;
12016
Chris Lattner31755a02007-04-15 01:02:18 +000012017 // Verify that the other block ends in a branch and is not otherwise empty.
12018 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012019 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012020 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012021 return false;
12022
Chris Lattner31755a02007-04-15 01:02:18 +000012023 // If the other block ends in an unconditional branch, check for the 'if then
12024 // else' case. there is an instruction before the branch.
12025 StoreInst *OtherStore = 0;
12026 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012027 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012028 // Skip over debugging info.
12029 while (isa<DbgInfoIntrinsic>(BBI) ||
12030 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12031 if (BBI==OtherBB->begin())
12032 return false;
12033 --BBI;
12034 }
12035 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012036 OtherStore = dyn_cast<StoreInst>(BBI);
12037 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12038 return false;
12039 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012040 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012041 // destinations is StoreBB, then we have the if/then case.
12042 if (OtherBr->getSuccessor(0) != StoreBB &&
12043 OtherBr->getSuccessor(1) != StoreBB)
12044 return false;
12045
12046 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012047 // if/then triangle. See if there is a store to the same ptr as SI that
12048 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012049 for (;; --BBI) {
12050 // Check to see if we find the matching store.
12051 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12052 if (OtherStore->getOperand(1) != SI.getOperand(1))
12053 return false;
12054 break;
12055 }
Eli Friedman6903a242008-06-13 22:02:12 +000012056 // If we find something that may be using or overwriting the stored
12057 // value, or if we run out of instructions, we can't do the xform.
12058 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012059 BBI == OtherBB->begin())
12060 return false;
12061 }
12062
12063 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012064 // make sure nothing reads or overwrites the stored value in
12065 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012066 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12067 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012068 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012069 return false;
12070 }
12071 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012072
Chris Lattner31755a02007-04-15 01:02:18 +000012073 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012074 Value *MergedVal = OtherStore->getOperand(0);
12075 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012076 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012077 PN->reserveOperandSpace(2);
12078 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012079 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12080 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012081 }
12082
12083 // Advance to a place where it is safe to insert the new store and
12084 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012085 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012086 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12087 OtherStore->isVolatile()), *BBI);
12088
12089 // Nuke the old stores.
12090 EraseInstFromFunction(SI);
12091 EraseInstFromFunction(*OtherStore);
12092 ++NumCombined;
12093 return true;
12094}
12095
Chris Lattner2f503e62005-01-31 05:36:43 +000012096
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012097Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12098 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012099 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012100 BasicBlock *TrueDest;
12101 BasicBlock *FalseDest;
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012102 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012103 !isa<Constant>(X)) {
12104 // Swap Destinations and condition...
12105 BI.setCondition(X);
12106 BI.setSuccessor(0, FalseDest);
12107 BI.setSuccessor(1, TrueDest);
12108 return &BI;
12109 }
12110
Reid Spencere4d87aa2006-12-23 06:05:41 +000012111 // Cannonicalize fcmp_one -> fcmp_oeq
12112 FCmpInst::Predicate FPred; Value *Y;
12113 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012114 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012115 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12116 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12117 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012118 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012119 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012120 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012121 // Swap Destinations and condition...
12122 BI.setCondition(NewSCC);
12123 BI.setSuccessor(0, FalseDest);
12124 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012125 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012126 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012127 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012128 return &BI;
12129 }
12130
12131 // Cannonicalize icmp_ne -> icmp_eq
12132 ICmpInst::Predicate IPred;
12133 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012134 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012135 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12136 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12137 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12138 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012139 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012140 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012141 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000012142 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012143 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012144 BI.setSuccessor(0, FalseDest);
12145 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012146 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012147 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012148 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012149 return &BI;
12150 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012151
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012152 return 0;
12153}
Chris Lattner0864acf2002-11-04 16:18:53 +000012154
Chris Lattner46238a62004-07-03 00:26:11 +000012155Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12156 Value *Cond = SI.getCondition();
12157 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12158 if (I->getOpcode() == Instruction::Add)
12159 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12160 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12161 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012162 SI.setOperand(i,
12163 Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012164 AddRHS));
12165 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000012166 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012167 return &SI;
12168 }
12169 }
12170 return 0;
12171}
12172
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012173Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012174 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012175
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012176 if (!EV.hasIndices())
12177 return ReplaceInstUsesWith(EV, Agg);
12178
12179 if (Constant *C = dyn_cast<Constant>(Agg)) {
12180 if (isa<UndefValue>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012181 return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012182
12183 if (isa<ConstantAggregateZero>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012184 return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012185
12186 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12187 // Extract the element indexed by the first index out of the constant
12188 Value *V = C->getOperand(*EV.idx_begin());
12189 if (EV.getNumIndices() > 1)
12190 // Extract the remaining indices out of the constant indexed by the
12191 // first index
12192 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12193 else
12194 return ReplaceInstUsesWith(EV, V);
12195 }
12196 return 0; // Can't handle other constants
12197 }
12198 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12199 // We're extracting from an insertvalue instruction, compare the indices
12200 const unsigned *exti, *exte, *insi, *inse;
12201 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12202 exte = EV.idx_end(), inse = IV->idx_end();
12203 exti != exte && insi != inse;
12204 ++exti, ++insi) {
12205 if (*insi != *exti)
12206 // The insert and extract both reference distinctly different elements.
12207 // This means the extract is not influenced by the insert, and we can
12208 // replace the aggregate operand of the extract with the aggregate
12209 // operand of the insert. i.e., replace
12210 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12211 // %E = extractvalue { i32, { i32 } } %I, 0
12212 // with
12213 // %E = extractvalue { i32, { i32 } } %A, 0
12214 return ExtractValueInst::Create(IV->getAggregateOperand(),
12215 EV.idx_begin(), EV.idx_end());
12216 }
12217 if (exti == exte && insi == inse)
12218 // Both iterators are at the end: Index lists are identical. Replace
12219 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12220 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12221 // with "i32 42"
12222 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12223 if (exti == exte) {
12224 // The extract list is a prefix of the insert list. i.e. replace
12225 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12226 // %E = extractvalue { i32, { i32 } } %I, 1
12227 // with
12228 // %X = extractvalue { i32, { i32 } } %A, 1
12229 // %E = insertvalue { i32 } %X, i32 42, 0
12230 // by switching the order of the insert and extract (though the
12231 // insertvalue should be left in, since it may have other uses).
12232 Value *NewEV = InsertNewInstBefore(
12233 ExtractValueInst::Create(IV->getAggregateOperand(),
12234 EV.idx_begin(), EV.idx_end()),
12235 EV);
12236 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12237 insi, inse);
12238 }
12239 if (insi == inse)
12240 // The insert list is a prefix of the extract list
12241 // We can simply remove the common indices from the extract and make it
12242 // operate on the inserted value instead of the insertvalue result.
12243 // i.e., replace
12244 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12245 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12246 // with
12247 // %E extractvalue { i32 } { i32 42 }, 0
12248 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12249 exti, exte);
12250 }
12251 // Can't simplify extracts from other values. Note that nested extracts are
12252 // already simplified implicitely by the above (extract ( extract (insert) )
12253 // will be translated into extract ( insert ( extract ) ) first and then just
12254 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012255 return 0;
12256}
12257
Chris Lattner220b0cf2006-03-05 00:22:33 +000012258/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12259/// is to leave as a vector operation.
12260static bool CheapToScalarize(Value *V, bool isConstant) {
12261 if (isa<ConstantAggregateZero>(V))
12262 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012263 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012264 if (isConstant) return true;
12265 // If all elts are the same, we can extract.
12266 Constant *Op0 = C->getOperand(0);
12267 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12268 if (C->getOperand(i) != Op0)
12269 return false;
12270 return true;
12271 }
12272 Instruction *I = dyn_cast<Instruction>(V);
12273 if (!I) return false;
12274
12275 // Insert element gets simplified to the inserted element or is deleted if
12276 // this is constant idx extract element and its a constant idx insertelt.
12277 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12278 isa<ConstantInt>(I->getOperand(2)))
12279 return true;
12280 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12281 return true;
12282 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12283 if (BO->hasOneUse() &&
12284 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12285 CheapToScalarize(BO->getOperand(1), isConstant)))
12286 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012287 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12288 if (CI->hasOneUse() &&
12289 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12290 CheapToScalarize(CI->getOperand(1), isConstant)))
12291 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012292
12293 return false;
12294}
12295
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012296/// Read and decode a shufflevector mask.
12297///
12298/// It turns undef elements into values that are larger than the number of
12299/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012300static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12301 unsigned NElts = SVI->getType()->getNumElements();
12302 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12303 return std::vector<unsigned>(NElts, 0);
12304 if (isa<UndefValue>(SVI->getOperand(2)))
12305 return std::vector<unsigned>(NElts, 2*NElts);
12306
12307 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012308 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012309 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12310 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012311 Result.push_back(NElts*2); // undef -> 8
12312 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012313 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012314 return Result;
12315}
12316
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012317/// FindScalarElement - Given a vector and an element number, see if the scalar
12318/// value is already around as a register, for example if it were inserted then
12319/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012320static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012321 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012322 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12323 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012324 unsigned Width = PTy->getNumElements();
12325 if (EltNo >= Width) // Out of range access.
Owen Andersond672ecb2009-07-03 00:17:18 +000012326 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012327
12328 if (isa<UndefValue>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012329 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012330 else if (isa<ConstantAggregateZero>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012331 return Context->getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012332 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012333 return CP->getOperand(EltNo);
12334 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12335 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012336 if (!isa<ConstantInt>(III->getOperand(2)))
12337 return 0;
12338 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012339
12340 // If this is an insert to the element we are looking for, return the
12341 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012342 if (EltNo == IIElt)
12343 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012344
12345 // Otherwise, the insertelement doesn't modify the value, recurse on its
12346 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012347 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012348 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012349 unsigned LHSWidth =
12350 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012351 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012352 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012353 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012354 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012355 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012356 else
Owen Andersond672ecb2009-07-03 00:17:18 +000012357 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012358 }
12359
12360 // Otherwise, we don't know.
12361 return 0;
12362}
12363
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012364Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012365 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012366 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012367 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012368
Dan Gohman07a96762007-07-16 14:29:03 +000012369 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012370 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012371 return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012372
Reid Spencer9d6565a2007-02-15 02:26:10 +000012373 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012374 // If vector val is constant with all elements the same, replace EI with
12375 // that element. When the elements are not identical, we cannot replace yet
12376 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012377 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012378 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012379 if (C->getOperand(i) != op0) {
12380 op0 = 0;
12381 break;
12382 }
12383 if (op0)
12384 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012385 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000012386
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012387 // If extracting a specified index from the vector, see if we can recursively
12388 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012389 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012390 unsigned IndexVal = IdxC->getZExtValue();
12391 unsigned VectorWidth =
12392 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12393
12394 // If this is extracting an invalid index, turn this into undef, to avoid
12395 // crashing the code below.
12396 if (IndexVal >= VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012397 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012398
Chris Lattner867b99f2006-10-05 06:55:50 +000012399 // This instruction only demands the single element from the input vector.
12400 // If the input vector has a single use, simplify it based on this use
12401 // property.
Chris Lattner85464092007-04-09 01:37:55 +000012402 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012403 APInt UndefElts(VectorWidth, 0);
12404 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012405 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012406 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012407 EI.setOperand(0, V);
12408 return &EI;
12409 }
12410 }
12411
Owen Andersond672ecb2009-07-03 00:17:18 +000012412 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012413 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012414
12415 // If the this extractelement is directly using a bitcast from a vector of
12416 // the same number of elements, see if we can find the source element from
12417 // it. In this case, we will end up needing to bitcast the scalars.
12418 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12419 if (const VectorType *VT =
12420 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12421 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012422 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12423 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012424 return new BitCastInst(Elt, EI.getType());
12425 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012426 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012427
Chris Lattner73fa49d2006-05-25 22:53:38 +000012428 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012429 if (I->hasOneUse()) {
12430 // Push extractelement into predecessor operation if legal and
12431 // profitable to do so
12432 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012433 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12434 if (CheapToScalarize(BO, isConstantElt)) {
12435 ExtractElementInst *newEI0 =
12436 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12437 EI.getName()+".lhs");
12438 ExtractElementInst *newEI1 =
12439 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12440 EI.getName()+".rhs");
12441 InsertNewInstBefore(newEI0, EI);
12442 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012443 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012444 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012445 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012446 unsigned AS =
12447 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012448 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +000012449 Context->getPointerType(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012450 GetElementPtrInst *GEP =
12451 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012452 InsertNewInstBefore(GEP, EI);
12453 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012454 }
12455 }
12456 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12457 // Extracting the inserted element?
12458 if (IE->getOperand(2) == EI.getOperand(1))
12459 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12460 // If the inserted and extracted elements are constants, they must not
12461 // be the same value, extract from the pre-inserted value instead.
12462 if (isa<Constant>(IE->getOperand(2)) &&
12463 isa<Constant>(EI.getOperand(1))) {
12464 AddUsesToWorkList(EI);
12465 EI.setOperand(0, IE->getOperand(0));
12466 return &EI;
12467 }
12468 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12469 // If this is extracting an element from a shufflevector, figure out where
12470 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012471 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12472 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012473 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012474 unsigned LHSWidth =
12475 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12476
12477 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012478 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012479 else if (SrcIdx < LHSWidth*2) {
12480 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012481 Src = SVI->getOperand(1);
12482 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012483 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012484 }
Owen Anderson9adc0ab2009-07-14 23:09:55 +000012485 return new ExtractElementInst(Src,
12486 Context->getConstantInt(Type::Int32Ty, SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012487 }
12488 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000012489 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012490 return 0;
12491}
12492
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012493/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12494/// elements from either LHS or RHS, return the shuffle mask and true.
12495/// Otherwise, return false.
12496static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012497 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012498 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012499 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12500 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012501 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012502
12503 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012504 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012505 return true;
12506 } else if (V == LHS) {
12507 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012508 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012509 return true;
12510 } else if (V == RHS) {
12511 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012512 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012513 return true;
12514 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12515 // If this is an insert of an extract from some other vector, include it.
12516 Value *VecOp = IEI->getOperand(0);
12517 Value *ScalarOp = IEI->getOperand(1);
12518 Value *IdxOp = IEI->getOperand(2);
12519
Chris Lattnerd929f062006-04-27 21:14:21 +000012520 if (!isa<ConstantInt>(IdxOp))
12521 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012522 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012523
12524 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12525 // Okay, we can handle this if the vector we are insertinting into is
12526 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012527 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012528 // If so, update the mask to reflect the inserted undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012529 Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012530 return true;
12531 }
12532 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12533 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012534 EI->getOperand(0)->getType() == V->getType()) {
12535 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012536 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012537
12538 // This must be extracting from either LHS or RHS.
12539 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12540 // Okay, we can handle this if the vector we are insertinting into is
12541 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012542 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012543 // If so, update the mask to reflect the inserted value.
12544 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012545 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012546 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012547 } else {
12548 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012549 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012550 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012551
12552 }
12553 return true;
12554 }
12555 }
12556 }
12557 }
12558 }
12559 // TODO: Handle shufflevector here!
12560
12561 return false;
12562}
12563
12564/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12565/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12566/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012567static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012568 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012569 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012570 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012571 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012572 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012573
12574 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012575 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012576 return V;
12577 } else if (isa<ConstantAggregateZero>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012578 Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012579 return V;
12580 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12581 // If this is an insert of an extract from some other vector, include it.
12582 Value *VecOp = IEI->getOperand(0);
12583 Value *ScalarOp = IEI->getOperand(1);
12584 Value *IdxOp = IEI->getOperand(2);
12585
12586 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12587 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12588 EI->getOperand(0)->getType() == V->getType()) {
12589 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012590 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12591 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012592
12593 // Either the extracted from or inserted into vector must be RHSVec,
12594 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012595 if (EI->getOperand(0) == RHS || RHS == 0) {
12596 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012597 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012598 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012599 Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012600 return V;
12601 }
12602
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012603 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012604 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12605 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012606 // Everything but the extracted element is replaced with the RHS.
12607 for (unsigned i = 0; i != NumElts; ++i) {
12608 if (i != InsertedIdx)
Owen Andersond672ecb2009-07-03 00:17:18 +000012609 Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012610 }
12611 return V;
12612 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012613
12614 // If this insertelement is a chain that comes from exactly these two
12615 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012616 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12617 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012618 return EI->getOperand(0);
12619
Chris Lattnerefb47352006-04-15 01:39:45 +000012620 }
12621 }
12622 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012623 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012624
12625 // Otherwise, can't do anything fancy. Return an identity vector.
12626 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012627 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012628 return V;
12629}
12630
12631Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12632 Value *VecOp = IE.getOperand(0);
12633 Value *ScalarOp = IE.getOperand(1);
12634 Value *IdxOp = IE.getOperand(2);
12635
Chris Lattner599ded12007-04-09 01:11:16 +000012636 // Inserting an undef or into an undefined place, remove this.
12637 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12638 ReplaceInstUsesWith(IE, VecOp);
12639
Chris Lattnerefb47352006-04-15 01:39:45 +000012640 // If the inserted element was extracted from some other vector, and if the
12641 // indexes are constant, try to turn this into a shufflevector operation.
12642 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12643 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12644 EI->getOperand(0)->getType() == IE.getType()) {
12645 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012646 unsigned ExtractedIdx =
12647 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012648 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012649
12650 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12651 return ReplaceInstUsesWith(IE, VecOp);
12652
12653 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersond672ecb2009-07-03 00:17:18 +000012654 return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012655
12656 // If we are extracting a value from a vector, then inserting it right
12657 // back into the same place, just use the input vector.
12658 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12659 return ReplaceInstUsesWith(IE, VecOp);
12660
12661 // We could theoretically do this for ANY input. However, doing so could
12662 // turn chains of insertelement instructions into a chain of shufflevector
12663 // instructions, and right now we do not merge shufflevectors. As such,
12664 // only do this in a situation where it is clear that there is benefit.
12665 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12666 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12667 // the values of VecOp, except then one read from EIOp0.
12668 // Build a new shuffle mask.
12669 std::vector<Constant*> Mask;
12670 if (isa<UndefValue>(VecOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000012671 Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012672 else {
12673 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Andersond672ecb2009-07-03 00:17:18 +000012674 Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012675 NumVectorElts));
12676 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012677 Mask[InsertedIdx] =
12678 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012679 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersond672ecb2009-07-03 00:17:18 +000012680 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012681 }
12682
12683 // If this insertelement isn't used by some other insertelement, turn it
12684 // (and any insertelements it points to), into one big shuffle.
12685 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12686 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012687 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012688 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12689 if (RHS == 0) RHS = Context->getUndef(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012690 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012691 return new ShuffleVectorInst(LHS, RHS,
12692 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012693 }
12694 }
12695 }
12696
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012697 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12698 APInt UndefElts(VWidth, 0);
12699 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12700 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12701 return &IE;
12702
Chris Lattnerefb47352006-04-15 01:39:45 +000012703 return 0;
12704}
12705
12706
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012707Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12708 Value *LHS = SVI.getOperand(0);
12709 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012710 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012711
12712 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012713
Chris Lattner867b99f2006-10-05 06:55:50 +000012714 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012715 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012716 return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012717
Dan Gohman488fbfc2008-09-09 18:11:14 +000012718 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012719
12720 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12721 return 0;
12722
Evan Cheng388df622009-02-03 10:05:09 +000012723 APInt UndefElts(VWidth, 0);
12724 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12725 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012726 LHS = SVI.getOperand(0);
12727 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012728 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012729 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012730
Chris Lattner863bcff2006-05-25 23:48:38 +000012731 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12732 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12733 if (LHS == RHS || isa<UndefValue>(LHS)) {
12734 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012735 // shuffle(undef,undef,mask) -> undef.
12736 return ReplaceInstUsesWith(SVI, LHS);
12737 }
12738
Chris Lattner863bcff2006-05-25 23:48:38 +000012739 // Remap any references to RHS to use LHS.
12740 std::vector<Constant*> Elts;
12741 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012742 if (Mask[i] >= 2*e)
Owen Andersond672ecb2009-07-03 00:17:18 +000012743 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012744 else {
12745 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012746 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012747 Mask[i] = 2*e; // Turn into undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012748 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman4ce96272008-08-06 18:17:32 +000012749 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012750 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Andersond672ecb2009-07-03 00:17:18 +000012751 Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012752 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012753 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012754 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012755 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +000012756 SVI.setOperand(1, Context->getUndef(RHS->getType()));
12757 SVI.setOperand(2, Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012758 LHS = SVI.getOperand(0);
12759 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012760 MadeChange = true;
12761 }
12762
Chris Lattner7b2e27922006-05-26 00:29:06 +000012763 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012764 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012765
Chris Lattner863bcff2006-05-25 23:48:38 +000012766 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12767 if (Mask[i] >= e*2) continue; // Ignore undef values.
12768 // Is this an identity shuffle of the LHS value?
12769 isLHSID &= (Mask[i] == i);
12770
12771 // Is this an identity shuffle of the RHS value?
12772 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012773 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012774
Chris Lattner863bcff2006-05-25 23:48:38 +000012775 // Eliminate identity shuffles.
12776 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12777 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012778
Chris Lattner7b2e27922006-05-26 00:29:06 +000012779 // If the LHS is a shufflevector itself, see if we can combine it with this
12780 // one without producing an unusual shuffle. Here we are really conservative:
12781 // we are absolutely afraid of producing a shuffle mask not in the input
12782 // program, because the code gen may not be smart enough to turn a merged
12783 // shuffle into two specific shuffles: it may produce worse code. As such,
12784 // we only merge two shuffles if the result is one of the two input shuffle
12785 // masks. In this case, merging the shuffles just removes one instruction,
12786 // which we know is safe. This is good for things like turning:
12787 // (splat(splat)) -> splat.
12788 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12789 if (isa<UndefValue>(RHS)) {
12790 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12791
12792 std::vector<unsigned> NewMask;
12793 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12794 if (Mask[i] >= 2*e)
12795 NewMask.push_back(2*e);
12796 else
12797 NewMask.push_back(LHSMask[Mask[i]]);
12798
12799 // If the result mask is equal to the src shuffle or this shuffle mask, do
12800 // the replacement.
12801 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012802 unsigned LHSInNElts =
12803 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012804 std::vector<Constant*> Elts;
12805 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012806 if (NewMask[i] >= LHSInNElts*2) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012807 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012808 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012809 Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012810 }
12811 }
12812 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12813 LHSSVI->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +000012814 Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012815 }
12816 }
12817 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012818
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012819 return MadeChange ? &SVI : 0;
12820}
12821
12822
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012823
Chris Lattnerea1c4542004-12-08 23:43:58 +000012824
12825/// TryToSinkInstruction - Try to move the specified instruction from its
12826/// current block into the beginning of DestBlock, which can only happen if it's
12827/// safe to move the instruction past all of the instructions between it and the
12828/// end of its block.
12829static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12830 assert(I->hasOneUse() && "Invariants didn't hold!");
12831
Chris Lattner108e9022005-10-27 17:13:11 +000012832 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012833 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012834 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012835
Chris Lattnerea1c4542004-12-08 23:43:58 +000012836 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012837 if (isa<AllocaInst>(I) && I->getParent() ==
12838 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012839 return false;
12840
Chris Lattner96a52a62004-12-09 07:14:34 +000012841 // We can only sink load instructions if there is nothing between the load and
12842 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012843 if (I->mayReadFromMemory()) {
12844 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012845 Scan != E; ++Scan)
12846 if (Scan->mayWriteToMemory())
12847 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012848 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012849
Dan Gohman02dea8b2008-05-23 21:05:58 +000012850 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012851
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012852 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012853 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012854 ++NumSunkInst;
12855 return true;
12856}
12857
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012858
12859/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12860/// all reachable code to the worklist.
12861///
12862/// This has a couple of tricks to make the code faster and more powerful. In
12863/// particular, we constant fold and DCE instructions as we go, to avoid adding
12864/// them to the worklist (this significantly speeds up instcombine on code where
12865/// many instructions are dead or constant). Additionally, if we find a branch
12866/// whose condition is a known constant, we only visit the reachable successors.
12867///
12868static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012869 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012870 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012871 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012872 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012873 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012874
Chris Lattner2c7718a2007-03-23 19:17:18 +000012875 while (!Worklist.empty()) {
12876 BB = Worklist.back();
12877 Worklist.pop_back();
12878
12879 // We have now visited this block! If we've already been here, ignore it.
12880 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012881
12882 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012883 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12884 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012885
Chris Lattner2c7718a2007-03-23 19:17:18 +000012886 // DCE instruction if trivially dead.
12887 if (isInstructionTriviallyDead(Inst)) {
12888 ++NumDeadInst;
12889 DOUT << "IC: DCE: " << *Inst;
12890 Inst->eraseFromParent();
12891 continue;
12892 }
12893
12894 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012895 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000012896 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12897 Inst->replaceAllUsesWith(C);
12898 ++NumConstProp;
12899 Inst->eraseFromParent();
12900 continue;
12901 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012902
Devang Patel7fe1dec2008-11-19 18:56:50 +000012903 // If there are two consecutive llvm.dbg.stoppoint calls then
12904 // it is likely that the optimizer deleted code in between these
12905 // two intrinsics.
12906 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12907 if (DBI_Next) {
12908 if (DBI_Prev
12909 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12910 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12911 IC.RemoveFromWorkList(DBI_Prev);
12912 DBI_Prev->eraseFromParent();
12913 }
12914 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012915 } else {
12916 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012917 }
12918
Chris Lattner2c7718a2007-03-23 19:17:18 +000012919 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012920 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012921
12922 // Recursively visit successors. If this is a branch or switch on a
12923 // constant, only visit the reachable successor.
12924 TerminatorInst *TI = BB->getTerminator();
12925 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12926 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12927 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012928 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012929 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012930 continue;
12931 }
12932 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12933 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12934 // See if this is an explicit destination.
12935 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12936 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012937 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012938 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012939 continue;
12940 }
12941
12942 // Otherwise it is the default destination.
12943 Worklist.push_back(SI->getSuccessor(0));
12944 continue;
12945 }
12946 }
12947
12948 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12949 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012950 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012951}
12952
Chris Lattnerec9c3582007-03-03 02:04:50 +000012953bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012954 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000012955 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012956
12957 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12958 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012959
Chris Lattnerb3d59702005-07-07 20:40:38 +000012960 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012961 // Do a depth-first traversal of the function, populate the worklist with
12962 // the reachable instructions. Ignore blocks that are not reachable. Keep
12963 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012964 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012965 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012966
Chris Lattnerb3d59702005-07-07 20:40:38 +000012967 // Do a quick scan over the function. If we find any blocks that are
12968 // unreachable, remove any instructions inside of them. This prevents
12969 // the instcombine code from having to deal with some bad special cases.
12970 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12971 if (!Visited.count(BB)) {
12972 Instruction *Term = BB->getTerminator();
12973 while (Term != BB->begin()) { // Remove instrs bottom-up
12974 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012975
Bill Wendlingb7427032006-11-26 09:46:52 +000012976 DOUT << "IC: DCE: " << *I;
Dale Johannesenff278b12009-03-10 21:19:49 +000012977 // A debug intrinsic shouldn't force another iteration if we weren't
12978 // going to do one without it.
12979 if (!isa<DbgInfoIntrinsic>(I)) {
12980 ++NumDeadInst;
12981 Changed = true;
12982 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012983 if (!I->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000012984 I->replaceAllUsesWith(Context->getUndef(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012985 I->eraseFromParent();
12986 }
12987 }
12988 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012989
Chris Lattnerdbab3862007-03-02 21:28:56 +000012990 while (!Worklist.empty()) {
12991 Instruction *I = RemoveOneFromWorkList();
12992 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012993
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012994 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012995 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012996 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012997 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012998 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012999 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013000
Bill Wendlingb7427032006-11-26 09:46:52 +000013001 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000013002
13003 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013004 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000013005 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013006 continue;
13007 }
Chris Lattner62b14df2002-09-02 04:59:56 +000013008
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013009 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000013010 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013011 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000013012
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013013 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000013014 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000013015 ReplaceInstUsesWith(*I, C);
13016
Chris Lattner62b14df2002-09-02 04:59:56 +000013017 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013018 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013019 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000013020 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013021 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000013022 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013023
Eli Friedmanfd2934f2009-07-15 22:13:34 +000013024 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013025 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000013026 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13027 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000013028 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13029 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000013030 if (NewC != CE) {
13031 i->set(NewC);
13032 Changed = true;
13033 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013034 }
13035
Chris Lattnerea1c4542004-12-08 23:43:58 +000013036 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013037 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013038 BasicBlock *BB = I->getParent();
13039 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13040 if (UserParent != BB) {
13041 bool UserIsSuccessor = false;
13042 // See if the user is one of our successors.
13043 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13044 if (*SI == UserParent) {
13045 UserIsSuccessor = true;
13046 break;
13047 }
13048
13049 // If the user is one of our immediate successors, and if that successor
13050 // only has us as a predecessors (we'd have to split the critical edge
13051 // otherwise), we can keep going.
13052 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13053 next(pred_begin(UserParent)) == pred_end(UserParent))
13054 // Okay, the CFG is simple enough, try to sink this instruction.
13055 Changed |= TryToSinkInstruction(I, UserParent);
13056 }
13057 }
13058
Chris Lattner8a2a3112001-12-14 16:52:21 +000013059 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000013060#ifndef NDEBUG
13061 std::string OrigI;
13062#endif
13063 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000013064 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013065 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013066 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013067 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013068 DOUT << "IC: Old = " << *I
13069 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000013070
Chris Lattnerf523d062004-06-09 05:08:07 +000013071 // Everything uses the new instruction now.
13072 I->replaceAllUsesWith(Result);
13073
13074 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013075 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000013076 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013077
Chris Lattner6934a042007-02-11 01:23:03 +000013078 // Move the name to the new instruction first.
13079 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013080
13081 // Insert the new instruction into the basic block...
13082 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013083 BasicBlock::iterator InsertPos = I;
13084
13085 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13086 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13087 ++InsertPos;
13088
13089 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013090
Chris Lattner00d51312004-05-01 23:27:23 +000013091 // Make sure that we reprocess all operands now that we reduced their
13092 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013093 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000013094
Chris Lattnerf523d062004-06-09 05:08:07 +000013095 // Instructions can end up on the worklist more than once. Make sure
13096 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013097 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013098
13099 // Erase the old instruction.
13100 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000013101 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013102#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000013103 DOUT << "IC: Mod = " << OrigI
13104 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000013105#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013106
Chris Lattner90ac28c2002-08-02 19:29:35 +000013107 // If the instruction was modified, it's possible that it is now dead.
13108 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013109 if (isInstructionTriviallyDead(I)) {
13110 // Make sure we process all operands now that we are reducing their
13111 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000013112 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000013113
Chris Lattner00d51312004-05-01 23:27:23 +000013114 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013115 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013116 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000013117 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000013118 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000013119 AddToWorkList(I);
13120 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013121 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013122 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013123 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013124 }
13125 }
13126
Chris Lattnerec9c3582007-03-03 02:04:50 +000013127 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000013128
13129 // Do an explicit clear, this shrinks the map if needed.
13130 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013131 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013132}
13133
Chris Lattnerec9c3582007-03-03 02:04:50 +000013134
13135bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013136 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13137
Chris Lattnerec9c3582007-03-03 02:04:50 +000013138 bool EverMadeChange = false;
13139
13140 // Iterate while there is work to do.
13141 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013142 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013143 EverMadeChange = true;
13144 return EverMadeChange;
13145}
13146
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013147FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013148 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013149}