blob: bda1c2153f01034a4a03ebfeb25739d6212ab4fc [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner173234a2008-06-02 01:18:21 +000045#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000046#include "llvm/Target/TargetData.h"
47#include "llvm/Transforms/Utils/BasicBlockUtils.h"
48#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000050#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000051#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000052#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000053#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000054#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000055#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000056#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000057#include "llvm/Support/Compiler.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000058#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000059#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000060#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000061#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000062#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000063#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000064#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000065#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000066#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000067using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000068using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000069
Chris Lattner0e5f4992006-12-19 21:40:18 +000070STATISTIC(NumCombined , "Number of insts combined");
71STATISTIC(NumConstProp, "Number of constant folds");
72STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000075
Chris Lattner0e5f4992006-12-19 21:40:18 +000076namespace {
Chris Lattner873ff012009-08-30 05:55:36 +000077 /// InstCombineWorklist - This is the worklist management logic for
78 /// InstCombine.
79 class InstCombineWorklist {
80 SmallVector<Instruction*, 256> Worklist;
81 DenseMap<Instruction*, unsigned> WorklistMap;
82
83 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
84 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
85 public:
86 InstCombineWorklist() {}
87
88 bool isEmpty() const { return Worklist.empty(); }
89
90 /// Add - Add the specified instruction to the worklist if it isn't already
91 /// in it.
92 void Add(Instruction *I) {
93 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
94 Worklist.push_back(I);
95 }
96
Chris Lattner7a1e9242009-08-30 06:13:40 +000097 // Remove - remove I from the worklist if it exists.
Chris Lattner873ff012009-08-30 05:55:36 +000098 void Remove(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 *RemoveOne() {
109 Instruction *I = Worklist.back();
110 Worklist.pop_back();
111 WorklistMap.erase(I);
112 return I;
113 }
114
115
116 /// Zap - check that the worklist is empty and nuke the backing store for
117 /// the map if it is large.
118 void Zap() {
119 assert(WorklistMap.empty() && "Worklist empty, but map not?");
120
121 // Do an explicit clear, this shrinks the map if needed.
122 WorklistMap.clear();
123 }
124 };
125} // end anonymous namespace.
126
127
128namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +0000129 class VISIBILITY_HIDDEN InstCombiner
130 : public FunctionPass,
131 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000132 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +0000133 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +0000134 public:
Chris Lattner7a1e9242009-08-30 06:13:40 +0000135 // Worklist of all of the instructions that need to be simplified.
136 InstCombineWorklist Worklist;
137
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000138 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +0000139 InstCombiner() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000140
Owen Andersone922c022009-07-22 00:24:57 +0000141 LLVMContext *Context;
142 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +0000143
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000144 /// AddUsersToWorkList - When an instruction is simplified, add all users of
145 /// the instruction to the work lists because they might get more simplified
146 /// now.
147 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000148 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000149 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000150 UI != UE; ++UI)
Chris Lattner7a1e9242009-08-30 06:13:40 +0000151 Worklist.Add(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000152 }
153
Chris Lattnerc3a3e362009-08-30 06:20:05 +0000154 /// AddOperandsToWorkList - When an instruction is simplified, add operands
155 /// to the work lists because they might get more simplified now.
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000156 ///
Chris Lattnerc3a3e362009-08-30 06:20:05 +0000157 void AddOperandsToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000158 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
159 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattner7a1e9242009-08-30 06:13:40 +0000160 Worklist.Add(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000161 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000162
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000163 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000164 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000165
166 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000167
Chris Lattner97e52e42002-04-28 21:27:06 +0000168 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000169 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000170 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000171 }
172
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000173 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000174
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000175 // Visitation implementation - Implement instruction combining for different
176 // instruction types. The semantics are as follows:
177 // Return Value:
178 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000179 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000180 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000181 //
Chris Lattner7e708292002-06-25 16:13:24 +0000182 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000183 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000184 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000185 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000186 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000187 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000188 Instruction *visitURem(BinaryOperator &I);
189 Instruction *visitSRem(BinaryOperator &I);
190 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000191 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000192 Instruction *commonRemTransforms(BinaryOperator &I);
193 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000194 Instruction *commonDivTransforms(BinaryOperator &I);
195 Instruction *commonIDivTransforms(BinaryOperator &I);
196 Instruction *visitUDiv(BinaryOperator &I);
197 Instruction *visitSDiv(BinaryOperator &I);
198 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000199 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000200 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000201 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000202 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000203 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000204 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000205 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000206 Instruction *visitOr (BinaryOperator &I);
207 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000208 Instruction *visitShl(BinaryOperator &I);
209 Instruction *visitAShr(BinaryOperator &I);
210 Instruction *visitLShr(BinaryOperator &I);
211 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000212 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
213 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000214 Instruction *visitFCmpInst(FCmpInst &I);
215 Instruction *visitICmpInst(ICmpInst &I);
216 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000217 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
218 Instruction *LHS,
219 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000220 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
221 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000222
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000223 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000224 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000225 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000226 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000227 Instruction *commonCastTransforms(CastInst &CI);
228 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000229 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000230 Instruction *visitTrunc(TruncInst &CI);
231 Instruction *visitZExt(ZExtInst &CI);
232 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000233 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000234 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000235 Instruction *visitFPToUI(FPToUIInst &FI);
236 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000237 Instruction *visitUIToFP(CastInst &CI);
238 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000239 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000240 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000241 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000242 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
243 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000244 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000245 Instruction *visitSelectInst(SelectInst &SI);
246 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000247 Instruction *visitCallInst(CallInst &CI);
248 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000249 Instruction *visitPHINode(PHINode &PN);
250 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000251 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000252 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000253 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000254 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000255 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000256 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000257 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000258 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000259 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000260 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000261
262 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000263 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000264
Chris Lattner9fe38862003-06-19 17:00:31 +0000265 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000266 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000267 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000268 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000269 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
270 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000271 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000272 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
273
Chris Lattner9fe38862003-06-19 17:00:31 +0000274
Chris Lattner28977af2004-04-05 01:30:19 +0000275 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000276 // InsertNewInstBefore - insert an instruction New before instruction Old
277 // in the program. Add the new instruction to the worklist.
278 //
Chris Lattner955f3312004-09-28 21:48:02 +0000279 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000280 assert(New && New->getParent() == 0 &&
281 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000282 BasicBlock *BB = Old.getParent();
283 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000284 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000285 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000286 }
287
Chris Lattner0c967662004-09-24 15:21:34 +0000288 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
289 /// This also adds the cast to the worklist. Finally, this returns the
290 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000291 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
292 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000293 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000294
Chris Lattnere2ed0572006-04-06 19:19:17 +0000295 if (Constant *CV = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000296 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000297
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000298 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000299 Worklist.Add(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000300 return C;
301 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000302
303 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
304 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
305 }
306
Chris Lattner0c967662004-09-24 15:21:34 +0000307
Chris Lattner8b170942002-08-09 23:47:40 +0000308 // ReplaceInstUsesWith - This method is to be used when an instruction is
309 // found to be dead, replacable with another preexisting expression. Here
310 // we add all uses of I to the worklist, replace all uses of I with the new
311 // value, then return I, so that the inst combiner will know that I was
312 // modified.
313 //
314 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000315 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner7a1e9242009-08-30 06:13:40 +0000316
317 // If we are replacing the instruction with itself, this must be in a
318 // segment of unreachable code, so just clobber the instruction.
319 if (&I == V)
320 V = UndefValue::get(I.getType());
321
322 I.replaceAllUsesWith(V);
323 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000324 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000325
326 // EraseInstFromFunction - When dealing with an instruction that has side
327 // effects or produces a void value, we can't rely on DCE to delete the
328 // instruction. Instead, visit methods should return the value returned by
329 // this function.
330 Instruction *EraseInstFromFunction(Instruction &I) {
331 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000332 // Make sure that we reprocess all operands now that we reduced their
333 // use counts.
334 if (I.getNumOperands() < 8)
Chris Lattnerc3a3e362009-08-30 06:20:05 +0000335 AddOperandsToWorkList(I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000336 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000337 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000338 return 0; // Don't do anything with FI
339 }
Chris Lattner173234a2008-06-02 01:18:21 +0000340
341 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
342 APInt &KnownOne, unsigned Depth = 0) const {
343 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
344 }
345
346 bool MaskedValueIsZero(Value *V, const APInt &Mask,
347 unsigned Depth = 0) const {
348 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
349 }
350 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
351 return llvm::ComputeNumSignBits(Op, TD, Depth);
352 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000353
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000354 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000355
Reid Spencere4d87aa2006-12-23 06:05:41 +0000356 /// SimplifyCommutative - This performs a few simplifications for
357 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000358 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000359
Reid Spencere4d87aa2006-12-23 06:05:41 +0000360 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
361 /// most-complex to least-complex order.
362 bool SimplifyCompare(CmpInst &I);
363
Chris Lattner886ab6c2009-01-31 08:15:18 +0000364 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
365 /// based on the demanded bits.
366 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
367 APInt& KnownZero, APInt& KnownOne,
368 unsigned Depth);
369 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000370 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000371 unsigned Depth=0);
372
373 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
374 /// SimplifyDemandedBits knows about. See if the instruction has any
375 /// properties that allow us to simplify its operands.
376 bool SimplifyDemandedInstructionBits(Instruction &Inst);
377
Evan Cheng388df622009-02-03 10:05:09 +0000378 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
379 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000380
Chris Lattner4e998b22004-09-29 05:07:12 +0000381 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
382 // PHI node as operand #0, see if we can fold the instruction into the PHI
383 // (which is only possible if all operands to the PHI are constants).
384 Instruction *FoldOpIntoPhi(Instruction &I);
385
Chris Lattnerbac32862004-11-14 19:13:23 +0000386 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
387 // operator and they all are only used by the PHI, PHI together their
388 // inputs, and do the operation once, to the result of the PHI.
389 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000390 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000391 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
392
Chris Lattner7da52b22006-11-01 04:51:18 +0000393
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000394 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
395 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000396
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000397 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000398 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000399 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000400 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000401 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000402 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000403 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000404 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000405 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000406
Chris Lattnerafe91a52006-06-15 19:07:26 +0000407
Reid Spencerc55b2432006-12-13 18:21:21 +0000408 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000409
Dan Gohman6de29f82009-06-15 22:12:54 +0000410 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000411 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000412 unsigned GetOrEnforceKnownAlignment(Value *V,
413 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000414
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000415 };
Chris Lattner873ff012009-08-30 05:55:36 +0000416} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000417
Dan Gohman844731a2008-05-13 00:00:25 +0000418char InstCombiner::ID = 0;
419static RegisterPass<InstCombiner>
420X("instcombine", "Combine redundant instructions");
421
Chris Lattner4f98c562003-03-10 21:43:22 +0000422// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000423// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000424static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000425 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000426 if (BinaryOperator::isNeg(V) ||
427 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000428 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000429 return 3;
430 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000431 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000432 if (isa<Argument>(V)) return 3;
433 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000434}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000435
Chris Lattnerc8802d22003-03-11 00:12:48 +0000436// isOnlyUse - Return true if this instruction will be deleted if we stop using
437// it.
438static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000439 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000440}
441
Chris Lattner4cb170c2004-02-23 06:38:22 +0000442// getPromotedType - Return the specified type promoted as it would be to pass
443// though a va_arg area...
444static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000445 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
446 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000447 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000448 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000449 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000450}
451
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000452/// getBitCastOperand - If the specified operand is a CastInst, a constant
453/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
454/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000455static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000456 if (Operator *O = dyn_cast<Operator>(V)) {
457 if (O->getOpcode() == Instruction::BitCast)
458 return O->getOperand(0);
459 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
460 if (GEP->hasAllZeroIndices())
461 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000462 }
Chris Lattnereed48272005-09-13 00:40:14 +0000463 return 0;
464}
465
Reid Spencer3da59db2006-11-27 01:05:10 +0000466/// This function is a wrapper around CastInst::isEliminableCastPair. It
467/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000468static Instruction::CastOps
469isEliminableCastPair(
470 const CastInst *CI, ///< The first cast instruction
471 unsigned opcode, ///< The opcode of the second cast instruction
472 const Type *DstTy, ///< The target type for the second cast instruction
473 TargetData *TD ///< The target data for pointer size
474) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000475
Reid Spencer3da59db2006-11-27 01:05:10 +0000476 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
477 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000478
Reid Spencer3da59db2006-11-27 01:05:10 +0000479 // Get the opcodes of the two Cast instructions
480 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
481 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000482
Chris Lattnera0e69692009-03-24 18:35:40 +0000483 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000484 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000485 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000486
487 // We don't want to form an inttoptr or ptrtoint that converts to an integer
488 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000489 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000490 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000491 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000492 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000493 Res = 0;
494
495 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000496}
497
498/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
499/// in any code being generated. It does not require codegen if V is simple
500/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000501static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
502 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000503 if (V->getType() == Ty || isa<Constant>(V)) return false;
504
Chris Lattner01575b72006-05-25 23:24:33 +0000505 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000506 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000507 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000508 return false;
509 return true;
510}
511
Chris Lattner4f98c562003-03-10 21:43:22 +0000512// SimplifyCommutative - This performs a few simplifications for commutative
513// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000514//
Chris Lattner4f98c562003-03-10 21:43:22 +0000515// 1. Order operands such that they are listed from right (least complex) to
516// left (most complex). This puts constants before unary operators before
517// binary operators.
518//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000519// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
520// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000521//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000522bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000523 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000524 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000525 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000526
Chris Lattner4f98c562003-03-10 21:43:22 +0000527 if (!I.isAssociative()) return Changed;
528 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000529 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
530 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
531 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000532 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000533 cast<Constant>(I.getOperand(1)),
534 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000535 I.setOperand(0, Op->getOperand(0));
536 I.setOperand(1, Folded);
537 return true;
538 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
539 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
540 isOnlyUse(Op) && isOnlyUse(Op1)) {
541 Constant *C1 = cast<Constant>(Op->getOperand(1));
542 Constant *C2 = cast<Constant>(Op1->getOperand(1));
543
544 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000545 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000546 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000547 Op1->getOperand(0),
548 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000549 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000550 I.setOperand(0, New);
551 I.setOperand(1, Folded);
552 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000553 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000554 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000555 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000556}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000557
Reid Spencere4d87aa2006-12-23 06:05:41 +0000558/// SimplifyCompare - For a CmpInst this function just orders the operands
559/// so that theyare listed from right (least complex) to left (most complex).
560/// This puts constants before unary operators before binary operators.
561bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman14ef4f02009-08-29 23:39:38 +0000562 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000563 return false;
564 I.swapOperands();
565 // Compare instructions are not associative so there's nothing else we can do.
566 return true;
567}
568
Chris Lattner8d969642003-03-10 23:06:50 +0000569// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
570// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000571//
Dan Gohman186a6362009-08-12 16:04:34 +0000572static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000573 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000574 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000575
Chris Lattner0ce85802004-12-14 20:08:06 +0000576 // Constants can be considered to be negated values if they can be folded.
577 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000578 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000579
580 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
581 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000582 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000583
Chris Lattner8d969642003-03-10 23:06:50 +0000584 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000585}
586
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000587// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
588// instruction if the LHS is a constant negative zero (which is the 'negate'
589// form).
590//
Dan Gohman186a6362009-08-12 16:04:34 +0000591static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000592 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000593 return BinaryOperator::getFNegArgument(V);
594
595 // Constants can be considered to be negated values if they can be folded.
596 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000597 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000598
599 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
600 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000601 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000602
603 return 0;
604}
605
Dan Gohman186a6362009-08-12 16:04:34 +0000606static inline Value *dyn_castNotVal(Value *V) {
Chris Lattner8d969642003-03-10 23:06:50 +0000607 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000608 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000609
610 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000611 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000612 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000613 return 0;
614}
615
Chris Lattnerc8802d22003-03-11 00:12:48 +0000616// dyn_castFoldableMul - If this value is a multiply that can be folded into
617// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000618// non-constant operand of the multiply, and set CST to point to the multiplier.
619// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000620//
Dan Gohman186a6362009-08-12 16:04:34 +0000621static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000622 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000623 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000624 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000625 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000626 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000627 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000628 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000629 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000630 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000631 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000632 CST = ConstantInt::get(V->getType()->getContext(),
633 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000634 return I->getOperand(0);
635 }
636 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000637 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000638}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000639
Reid Spencer7177c3a2007-03-25 05:33:51 +0000640/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000641static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000642 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000643 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000644}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000645/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000646static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000647 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000648 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000649}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000650/// MultiplyOverflows - True if the multiply can not be expressed in an int
651/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000652static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000653 uint32_t W = C1->getBitWidth();
654 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
655 if (sign) {
656 LHSExt.sext(W * 2);
657 RHSExt.sext(W * 2);
658 } else {
659 LHSExt.zext(W * 2);
660 RHSExt.zext(W * 2);
661 }
662
663 APInt MulExt = LHSExt * RHSExt;
664
665 if (sign) {
666 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
667 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
668 return MulExt.slt(Min) || MulExt.sgt(Max);
669 } else
670 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
671}
Chris Lattner955f3312004-09-28 21:48:02 +0000672
Reid Spencere7816b52007-03-08 01:52:58 +0000673
Chris Lattner255d8912006-02-11 09:31:47 +0000674/// ShrinkDemandedConstant - Check to see if the specified operand of the
675/// specified instruction is a constant integer. If so, check to see if there
676/// are any bits set in the constant that are not demanded. If so, shrink the
677/// constant and return true.
678static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000679 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000680 assert(I && "No instruction?");
681 assert(OpNo < I->getNumOperands() && "Operand index too large");
682
683 // If the operand is not a constant integer, nothing to do.
684 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
685 if (!OpC) return false;
686
687 // If there are no bits set that aren't demanded, nothing to do.
688 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
689 if ((~Demanded & OpC->getValue()) == 0)
690 return false;
691
692 // This instruction is producing bits that are not demanded. Shrink the RHS.
693 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000694 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000695 return true;
696}
697
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000698// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
699// set of known zero and one bits, compute the maximum and minimum values that
700// could have the specified known zero and known one bits, returning them in
701// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000702static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000703 const APInt& KnownOne,
704 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000705 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
706 KnownZero.getBitWidth() == Min.getBitWidth() &&
707 KnownZero.getBitWidth() == Max.getBitWidth() &&
708 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000709 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000710
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000711 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
712 // bit if it is unknown.
713 Min = KnownOne;
714 Max = KnownOne|UnknownBits;
715
Dan Gohman1c8491e2009-04-25 17:12:48 +0000716 if (UnknownBits.isNegative()) { // Sign bit is unknown
717 Min.set(Min.getBitWidth()-1);
718 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000719 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000720}
721
722// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
723// a set of known zero and one bits, compute the maximum and minimum values that
724// could have the specified known zero and known one bits, returning them in
725// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000726static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000727 const APInt &KnownOne,
728 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000729 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
730 KnownZero.getBitWidth() == Min.getBitWidth() &&
731 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000732 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000733 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000734
735 // The minimum value is when the unknown bits are all zeros.
736 Min = KnownOne;
737 // The maximum value is when the unknown bits are all ones.
738 Max = KnownOne|UnknownBits;
739}
Chris Lattner255d8912006-02-11 09:31:47 +0000740
Chris Lattner886ab6c2009-01-31 08:15:18 +0000741/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
742/// SimplifyDemandedBits knows about. See if the instruction has any
743/// properties that allow us to simplify its operands.
744bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000745 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000746 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
747 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
748
749 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
750 KnownZero, KnownOne, 0);
751 if (V == 0) return false;
752 if (V == &Inst) return true;
753 ReplaceInstUsesWith(Inst, V);
754 return true;
755}
756
757/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
758/// specified instruction operand if possible, updating it in place. It returns
759/// true if it made any change and false otherwise.
760bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
761 APInt &KnownZero, APInt &KnownOne,
762 unsigned Depth) {
763 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
764 KnownZero, KnownOne, Depth);
765 if (NewVal == 0) return false;
766 U.set(NewVal);
767 return true;
768}
769
770
771/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
772/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000773/// that only the bits set in DemandedMask of the result of V are ever used
774/// downstream. Consequently, depending on the mask and V, it may be possible
775/// to replace V with a constant or one of its operands. In such cases, this
776/// function does the replacement and returns true. In all other cases, it
777/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000778/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000779/// to be zero in the expression. These are provided to potentially allow the
780/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
781/// the expression. KnownOne and KnownZero always follow the invariant that
782/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
783/// the bits in KnownOne and KnownZero may only be accurate for those bits set
784/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
785/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000786///
787/// This returns null if it did not change anything and it permits no
788/// simplification. This returns V itself if it did some simplification of V's
789/// operands based on the information about what bits are demanded. This returns
790/// some other non-null value if it found out that V is equal to another value
791/// in the context where the specified bits are demanded, but not for all users.
792Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
793 APInt &KnownZero, APInt &KnownOne,
794 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000795 assert(V != 0 && "Null pointer of Value???");
796 assert(Depth <= 6 && "Limit Search Depth");
797 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000798 const Type *VTy = V->getType();
799 assert((TD || !isa<PointerType>(VTy)) &&
800 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000801 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
802 (!VTy->isIntOrIntVector() ||
803 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000804 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000805 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000806 "Value *V, DemandedMask, KnownZero and KnownOne "
807 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000808 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
809 // We know all of the bits for a constant!
810 KnownOne = CI->getValue() & DemandedMask;
811 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000812 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000813 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000814 if (isa<ConstantPointerNull>(V)) {
815 // We know all of the bits for a constant!
816 KnownOne.clear();
817 KnownZero = DemandedMask;
818 return 0;
819 }
820
Chris Lattner08d2cc72009-01-31 07:26:06 +0000821 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000822 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000823 if (DemandedMask == 0) { // Not demanding any bits from V.
824 if (isa<UndefValue>(V))
825 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000826 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000827 }
828
Chris Lattner4598c942009-01-31 08:24:16 +0000829 if (Depth == 6) // Limit search depth.
830 return 0;
831
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000832 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
833 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
834
Dan Gohman1c8491e2009-04-25 17:12:48 +0000835 Instruction *I = dyn_cast<Instruction>(V);
836 if (!I) {
837 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
838 return 0; // Only analyze instructions.
839 }
840
Chris Lattner4598c942009-01-31 08:24:16 +0000841 // If there are multiple uses of this value and we aren't at the root, then
842 // we can't do any simplifications of the operands, because DemandedMask
843 // only reflects the bits demanded by *one* of the users.
844 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000845 // Despite the fact that we can't simplify this instruction in all User's
846 // context, we can at least compute the knownzero/knownone bits, and we can
847 // do simplifications that apply to *just* the one user if we know that
848 // this instruction has a simpler value in that context.
849 if (I->getOpcode() == Instruction::And) {
850 // If either the LHS or the RHS are Zero, the result is zero.
851 ComputeMaskedBits(I->getOperand(1), DemandedMask,
852 RHSKnownZero, RHSKnownOne, Depth+1);
853 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
854 LHSKnownZero, LHSKnownOne, Depth+1);
855
856 // If all of the demanded bits are known 1 on one side, return the other.
857 // These bits cannot contribute to the result of the 'and' in this
858 // context.
859 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
860 (DemandedMask & ~LHSKnownZero))
861 return I->getOperand(0);
862 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
863 (DemandedMask & ~RHSKnownZero))
864 return I->getOperand(1);
865
866 // If all of the demanded bits in the inputs are known zeros, return zero.
867 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000868 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000869
870 } else if (I->getOpcode() == Instruction::Or) {
871 // We can simplify (X|Y) -> X or Y in the user's context if we know that
872 // only bits from X or Y are demanded.
873
874 // If either the LHS or the RHS are One, the result is One.
875 ComputeMaskedBits(I->getOperand(1), DemandedMask,
876 RHSKnownZero, RHSKnownOne, Depth+1);
877 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
878 LHSKnownZero, LHSKnownOne, Depth+1);
879
880 // If all of the demanded bits are known zero on one side, return the
881 // other. These bits cannot contribute to the result of the 'or' in this
882 // context.
883 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
884 (DemandedMask & ~LHSKnownOne))
885 return I->getOperand(0);
886 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
887 (DemandedMask & ~RHSKnownOne))
888 return I->getOperand(1);
889
890 // If all of the potentially set bits on one side are known to be set on
891 // the other side, just use the 'other' side.
892 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
893 (DemandedMask & (~RHSKnownZero)))
894 return I->getOperand(0);
895 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
896 (DemandedMask & (~LHSKnownZero)))
897 return I->getOperand(1);
898 }
899
Chris Lattner4598c942009-01-31 08:24:16 +0000900 // Compute the KnownZero/KnownOne bits to simplify things downstream.
901 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
902 return 0;
903 }
904
905 // If this is the root being simplified, allow it to have multiple uses,
906 // just set the DemandedMask to all bits so that we can try to simplify the
907 // operands. This allows visitTruncInst (for example) to simplify the
908 // operand of a trunc without duplicating all the logic below.
909 if (Depth == 0 && !V->hasOneUse())
910 DemandedMask = APInt::getAllOnesValue(BitWidth);
911
Reid Spencer8cb68342007-03-12 17:25:59 +0000912 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000913 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000914 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000915 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000916 case Instruction::And:
917 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000918 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
919 RHSKnownZero, RHSKnownOne, Depth+1) ||
920 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000921 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000922 return I;
923 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
924 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000925
926 // If all of the demanded bits are known 1 on one side, return the other.
927 // These bits cannot contribute to the result of the 'and'.
928 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
929 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000930 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000931 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
932 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000933 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000934
935 // If all of the demanded bits in the inputs are known zeros, return zero.
936 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000937 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000938
939 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000940 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000941 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000942
943 // Output known-1 bits are only known if set in both the LHS & RHS.
944 RHSKnownOne &= LHSKnownOne;
945 // Output known-0 are known to be clear if zero in either the LHS | RHS.
946 RHSKnownZero |= LHSKnownZero;
947 break;
948 case Instruction::Or:
949 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000950 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
951 RHSKnownZero, RHSKnownOne, Depth+1) ||
952 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000953 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000954 return I;
955 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
956 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000957
958 // If all of the demanded bits are known zero on one side, return the other.
959 // These bits cannot contribute to the result of the 'or'.
960 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
961 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000962 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000963 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
964 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000965 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000966
967 // If all of the potentially set bits on one side are known to be set on
968 // the other side, just use the 'other' side.
969 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
970 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000971 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000972 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
973 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000974 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000975
976 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000977 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000978 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000979
980 // Output known-0 bits are only known if clear in both the LHS & RHS.
981 RHSKnownZero &= LHSKnownZero;
982 // Output known-1 are known to be set if set in either the LHS | RHS.
983 RHSKnownOne |= LHSKnownOne;
984 break;
985 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000986 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
987 RHSKnownZero, RHSKnownOne, Depth+1) ||
988 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000989 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000990 return I;
991 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
992 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000993
994 // If all of the demanded bits are known zero on one side, return the other.
995 // These bits cannot contribute to the result of the 'xor'.
996 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000997 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000998 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000999 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001000
1001 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1002 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1003 (RHSKnownOne & LHSKnownOne);
1004 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1005 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1006 (RHSKnownOne & LHSKnownZero);
1007
1008 // If all of the demanded bits are known to be zero on one side or the
1009 // other, turn this into an *inclusive* or.
1010 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1011 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1012 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001013 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001014 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001015 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001016 }
1017
1018 // If all of the demanded bits on one side are known, and all of the set
1019 // bits on that side are also known to be set on the other side, turn this
1020 // into an AND, as we know the bits will be cleared.
1021 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1022 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1023 // all known
1024 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001025 Constant *AndC = Constant::getIntegerValue(VTy,
1026 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001027 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001028 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001029 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001030 }
1031 }
1032
1033 // If the RHS is a constant, see if we can simplify it.
1034 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001035 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001036 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001037
1038 RHSKnownZero = KnownZeroOut;
1039 RHSKnownOne = KnownOneOut;
1040 break;
1041 }
1042 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001043 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1044 RHSKnownZero, RHSKnownOne, Depth+1) ||
1045 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001046 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001047 return I;
1048 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1049 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001050
1051 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001052 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1053 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001054 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001055
1056 // Only known if known in both the LHS and RHS.
1057 RHSKnownOne &= LHSKnownOne;
1058 RHSKnownZero &= LHSKnownZero;
1059 break;
1060 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001061 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001062 DemandedMask.zext(truncBf);
1063 RHSKnownZero.zext(truncBf);
1064 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001065 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001066 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001067 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001068 DemandedMask.trunc(BitWidth);
1069 RHSKnownZero.trunc(BitWidth);
1070 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001071 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001072 break;
1073 }
1074 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001075 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001076 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001077
1078 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1079 if (const VectorType *SrcVTy =
1080 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1081 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1082 // Don't touch a bitcast between vectors of different element counts.
1083 return false;
1084 } else
1085 // Don't touch a scalar-to-vector bitcast.
1086 return false;
1087 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1088 // Don't touch a vector-to-scalar bitcast.
1089 return false;
1090
Chris Lattner886ab6c2009-01-31 08:15:18 +00001091 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001092 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001093 return I;
1094 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001095 break;
1096 case Instruction::ZExt: {
1097 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001098 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001099
Zhou Shengd48653a2007-03-29 04:45:55 +00001100 DemandedMask.trunc(SrcBitWidth);
1101 RHSKnownZero.trunc(SrcBitWidth);
1102 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001103 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001104 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001105 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001106 DemandedMask.zext(BitWidth);
1107 RHSKnownZero.zext(BitWidth);
1108 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001109 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001110 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001111 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001112 break;
1113 }
1114 case Instruction::SExt: {
1115 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001116 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001117
Reid Spencer8cb68342007-03-12 17:25:59 +00001118 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001119 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001120
Zhou Sheng01542f32007-03-29 02:26:30 +00001121 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001122 // If any of the sign extended bits are demanded, we know that the sign
1123 // bit is demanded.
1124 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001125 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001126
Zhou Shengd48653a2007-03-29 04:45:55 +00001127 InputDemandedBits.trunc(SrcBitWidth);
1128 RHSKnownZero.trunc(SrcBitWidth);
1129 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001130 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001131 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001132 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001133 InputDemandedBits.zext(BitWidth);
1134 RHSKnownZero.zext(BitWidth);
1135 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001136 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001137
1138 // If the sign bit of the input is known set or clear, then we know the
1139 // top bits of the result.
1140
1141 // If the input sign bit is known zero, or if the NewBits are not demanded
1142 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001143 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001144 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001145 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1146 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001147 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001148 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001149 }
1150 break;
1151 }
1152 case Instruction::Add: {
1153 // Figure out what the input bits are. If the top bits of the and result
1154 // are not demanded, then the add doesn't demand them from its input
1155 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001156 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001157
1158 // If there is a constant on the RHS, there are a variety of xformations
1159 // we can do.
1160 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1161 // If null, this should be simplified elsewhere. Some of the xforms here
1162 // won't work if the RHS is zero.
1163 if (RHS->isZero())
1164 break;
1165
1166 // If the top bit of the output is demanded, demand everything from the
1167 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001168 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001169
1170 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001171 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001172 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001173 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001174
1175 // If the RHS of the add has bits set that can't affect the input, reduce
1176 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001177 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001178 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001179
1180 // Avoid excess work.
1181 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1182 break;
1183
1184 // Turn it into OR if input bits are zero.
1185 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1186 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001187 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001188 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001189 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001190 }
1191
1192 // We can say something about the output known-zero and known-one bits,
1193 // depending on potential carries from the input constant and the
1194 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1195 // bits set and the RHS constant is 0x01001, then we know we have a known
1196 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1197
1198 // To compute this, we first compute the potential carry bits. These are
1199 // the bits which may be modified. I'm not aware of a better way to do
1200 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001201 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001202 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001203
1204 // Now that we know which bits have carries, compute the known-1/0 sets.
1205
1206 // Bits are known one if they are known zero in one operand and one in the
1207 // other, and there is no input carry.
1208 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1209 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1210
1211 // Bits are known zero if they are known zero in both operands and there
1212 // is no input carry.
1213 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1214 } else {
1215 // If the high-bits of this ADD are not demanded, then it does not demand
1216 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001217 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001218 // Right fill the mask of bits for this ADD to demand the most
1219 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001220 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001221 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1222 LHSKnownZero, LHSKnownOne, Depth+1) ||
1223 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001224 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001225 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001226 }
1227 }
1228 break;
1229 }
1230 case Instruction::Sub:
1231 // If the high-bits of this SUB are not demanded, then it does not demand
1232 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001233 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001234 // Right fill the mask of bits for this SUB to demand the most
1235 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001236 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001237 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001238 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1239 LHSKnownZero, LHSKnownOne, Depth+1) ||
1240 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001241 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001242 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001243 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001244 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1245 // the known zeros and ones.
1246 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001247 break;
1248 case Instruction::Shl:
1249 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001250 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001251 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001252 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001253 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001254 return I;
1255 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001256 RHSKnownZero <<= ShiftAmt;
1257 RHSKnownOne <<= ShiftAmt;
1258 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001259 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001260 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001261 }
1262 break;
1263 case Instruction::LShr:
1264 // For a logical shift right
1265 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001266 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001267
Reid Spencer8cb68342007-03-12 17:25:59 +00001268 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001269 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001270 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001271 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001272 return I;
1273 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001274 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1275 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001276 if (ShiftAmt) {
1277 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001278 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001279 RHSKnownZero |= HighBits; // high bits known zero.
1280 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001281 }
1282 break;
1283 case Instruction::AShr:
1284 // If this is an arithmetic shift right and only the low-bit is set, we can
1285 // always convert this into a logical shr, even if the shift amount is
1286 // variable. The low bit of the shift cannot be an input sign bit unless
1287 // the shift amount is >= the size of the datatype, which is undefined.
1288 if (DemandedMask == 1) {
1289 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001290 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001291 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001292 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001293 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001294
1295 // If the sign bit is the only bit demanded by this ashr, then there is no
1296 // need to do it, the shift doesn't change the high bit.
1297 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001298 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001299
1300 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001301 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001302
Reid Spencer8cb68342007-03-12 17:25:59 +00001303 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001304 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001305 // If any of the "high bits" are demanded, we should set the sign bit as
1306 // demanded.
1307 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1308 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001309 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001310 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001311 return I;
1312 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001313 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001314 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001315 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1316 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1317
1318 // Handle the sign bits.
1319 APInt SignBit(APInt::getSignBit(BitWidth));
1320 // Adjust to where it is now in the mask.
1321 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1322
1323 // If the input sign bit is known to be zero, or if none of the top bits
1324 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001325 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001326 (HighBits & ~DemandedMask) == HighBits) {
1327 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001328 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001329 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001330 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001331 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1332 RHSKnownOne |= HighBits;
1333 }
1334 }
1335 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001336 case Instruction::SRem:
1337 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001338 APInt RA = Rem->getValue().abs();
1339 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001340 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001341 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001342
Nick Lewycky8e394322008-11-02 02:41:50 +00001343 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001344 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001345 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001346 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001347 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001348
1349 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1350 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001351
1352 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001353
Chris Lattner886ab6c2009-01-31 08:15:18 +00001354 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001355 }
1356 }
1357 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001358 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001359 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1360 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001361 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1362 KnownZero2, KnownOne2, Depth+1) ||
1363 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001364 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001365 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001366
Chris Lattner455e9ab2009-01-21 18:09:24 +00001367 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001368 Leaders = std::max(Leaders,
1369 KnownZero2.countLeadingOnes());
1370 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001371 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001372 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001373 case Instruction::Call:
1374 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1375 switch (II->getIntrinsicID()) {
1376 default: break;
1377 case Intrinsic::bswap: {
1378 // If the only bits demanded come from one byte of the bswap result,
1379 // just shift the input byte into position to eliminate the bswap.
1380 unsigned NLZ = DemandedMask.countLeadingZeros();
1381 unsigned NTZ = DemandedMask.countTrailingZeros();
1382
1383 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1384 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1385 // have 14 leading zeros, round to 8.
1386 NLZ &= ~7;
1387 NTZ &= ~7;
1388 // If we need exactly one byte, we can do this transformation.
1389 if (BitWidth-NLZ-NTZ == 8) {
1390 unsigned ResultBit = NTZ;
1391 unsigned InputBit = BitWidth-NTZ-8;
1392
1393 // Replace this with either a left or right shift to get the byte into
1394 // the right place.
1395 Instruction *NewVal;
1396 if (InputBit > ResultBit)
1397 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001398 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001399 else
1400 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001401 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001402 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001403 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001404 }
1405
1406 // TODO: Could compute known zero/one bits based on the input.
1407 break;
1408 }
1409 }
1410 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001411 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001412 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001413 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001414
1415 // If the client is only demanding bits that we know, return the known
1416 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001417 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1418 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001419 return false;
1420}
1421
Chris Lattner867b99f2006-10-05 06:55:50 +00001422
Mon P Wangaeb06d22008-11-10 04:46:22 +00001423/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001424/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001425/// actually used by the caller. This method analyzes which elements of the
1426/// operand are undef and returns that information in UndefElts.
1427///
1428/// If the information about demanded elements can be used to simplify the
1429/// operation, the operation is simplified, then the resultant value is
1430/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001431Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1432 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001433 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001434 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001435 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001436 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001437
1438 if (isa<UndefValue>(V)) {
1439 // If the entire vector is undefined, just return this info.
1440 UndefElts = EltMask;
1441 return 0;
1442 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1443 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001444 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001445 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001446
Chris Lattner867b99f2006-10-05 06:55:50 +00001447 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001448 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1449 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001450 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001451
1452 std::vector<Constant*> Elts;
1453 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001454 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001455 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001456 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001457 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1458 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001459 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001460 } else { // Otherwise, defined.
1461 Elts.push_back(CP->getOperand(i));
1462 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001463
Chris Lattner867b99f2006-10-05 06:55:50 +00001464 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001465 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001466 return NewCP != CP ? NewCP : 0;
1467 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001468 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001469 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001470
1471 // Check if this is identity. If so, return 0 since we are not simplifying
1472 // anything.
1473 if (DemandedElts == ((1ULL << VWidth) -1))
1474 return 0;
1475
Reid Spencer9d6565a2007-02-15 02:26:10 +00001476 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001477 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001478 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001479 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001480 for (unsigned i = 0; i != VWidth; ++i) {
1481 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1482 Elts.push_back(Elt);
1483 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001484 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001485 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001486 }
1487
Dan Gohman488fbfc2008-09-09 18:11:14 +00001488 // Limit search depth.
1489 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001490 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001491
1492 // If multiple users are using the root value, procede with
1493 // simplification conservatively assuming that all elements
1494 // are needed.
1495 if (!V->hasOneUse()) {
1496 // Quit if we find multiple users of a non-root value though.
1497 // They'll be handled when it's their turn to be visited by
1498 // the main instcombine process.
1499 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001500 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001501 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001502
1503 // Conservatively assume that all elements are needed.
1504 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001505 }
1506
1507 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001508 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001509
1510 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001511 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001512 Value *TmpV;
1513 switch (I->getOpcode()) {
1514 default: break;
1515
1516 case Instruction::InsertElement: {
1517 // If this is a variable index, we don't know which element it overwrites.
1518 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001519 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001520 if (Idx == 0) {
1521 // Note that we can't propagate undef elt info, because we don't know
1522 // which elt is getting updated.
1523 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1524 UndefElts2, Depth+1);
1525 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1526 break;
1527 }
1528
1529 // If this is inserting an element that isn't demanded, remove this
1530 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001531 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001532 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1533 Worklist.Add(I);
1534 return I->getOperand(0);
1535 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001536
1537 // Otherwise, the element inserted overwrites whatever was there, so the
1538 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001539 APInt DemandedElts2 = DemandedElts;
1540 DemandedElts2.clear(IdxNo);
1541 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001542 UndefElts, Depth+1);
1543 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1544
1545 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001546 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001547 break;
1548 }
1549 case Instruction::ShuffleVector: {
1550 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001551 uint64_t LHSVWidth =
1552 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001553 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001554 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001555 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001556 unsigned MaskVal = Shuffle->getMaskValue(i);
1557 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001558 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001559 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001560 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001561 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001562 else
Evan Cheng388df622009-02-03 10:05:09 +00001563 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001564 }
1565 }
1566 }
1567
Nate Begeman7b254672009-02-11 22:36:25 +00001568 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001569 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001570 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001571 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1572
Nate Begeman7b254672009-02-11 22:36:25 +00001573 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001574 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1575 UndefElts3, Depth+1);
1576 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1577
1578 bool NewUndefElts = false;
1579 for (unsigned i = 0; i < VWidth; i++) {
1580 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001581 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001582 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001583 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001584 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001585 NewUndefElts = true;
1586 UndefElts.set(i);
1587 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001588 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001589 if (UndefElts3[MaskVal - LHSVWidth]) {
1590 NewUndefElts = true;
1591 UndefElts.set(i);
1592 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001593 }
1594 }
1595
1596 if (NewUndefElts) {
1597 // Add additional discovered undefs.
1598 std::vector<Constant*> Elts;
1599 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001600 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001601 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001602 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001603 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001604 Shuffle->getMaskValue(i)));
1605 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001606 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001607 MadeChange = true;
1608 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001609 break;
1610 }
Chris Lattner69878332007-04-14 22:29:23 +00001611 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001612 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001613 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1614 if (!VTy) break;
1615 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001616 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001617 unsigned Ratio;
1618
1619 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001620 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001621 // elements as are demanded of us.
1622 Ratio = 1;
1623 InputDemandedElts = DemandedElts;
1624 } else if (VWidth > InVWidth) {
1625 // Untested so far.
1626 break;
1627
1628 // If there are more elements in the result than there are in the source,
1629 // then an input element is live if any of the corresponding output
1630 // elements are live.
1631 Ratio = VWidth/InVWidth;
1632 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001633 if (DemandedElts[OutIdx])
1634 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001635 }
1636 } else {
1637 // Untested so far.
1638 break;
1639
1640 // If there are more elements in the source than there are in the result,
1641 // then an input element is live if the corresponding output element is
1642 // live.
1643 Ratio = InVWidth/VWidth;
1644 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001645 if (DemandedElts[InIdx/Ratio])
1646 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001647 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001648
Chris Lattner69878332007-04-14 22:29:23 +00001649 // div/rem demand all inputs, because they don't want divide by zero.
1650 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1651 UndefElts2, Depth+1);
1652 if (TmpV) {
1653 I->setOperand(0, TmpV);
1654 MadeChange = true;
1655 }
1656
1657 UndefElts = UndefElts2;
1658 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001659 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001660 // If there are more elements in the result than there are in the source,
1661 // then an output element is undef if the corresponding input element is
1662 // undef.
1663 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001664 if (UndefElts2[OutIdx/Ratio])
1665 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001666 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001667 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001668 // If there are more elements in the source than there are in the result,
1669 // then a result element is undef if all of the corresponding input
1670 // elements are undef.
1671 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1672 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001673 if (!UndefElts2[InIdx]) // Not undef?
1674 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001675 }
1676 break;
1677 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001678 case Instruction::And:
1679 case Instruction::Or:
1680 case Instruction::Xor:
1681 case Instruction::Add:
1682 case Instruction::Sub:
1683 case Instruction::Mul:
1684 // div/rem demand all inputs, because they don't want divide by zero.
1685 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1686 UndefElts, Depth+1);
1687 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1688 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1689 UndefElts2, Depth+1);
1690 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1691
1692 // Output elements are undefined if both are undefined. Consider things
1693 // like undef&0. The result is known zero, not undef.
1694 UndefElts &= UndefElts2;
1695 break;
1696
1697 case Instruction::Call: {
1698 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1699 if (!II) break;
1700 switch (II->getIntrinsicID()) {
1701 default: break;
1702
1703 // Binary vector operations that work column-wise. A dest element is a
1704 // function of the corresponding input elements from the two inputs.
1705 case Intrinsic::x86_sse_sub_ss:
1706 case Intrinsic::x86_sse_mul_ss:
1707 case Intrinsic::x86_sse_min_ss:
1708 case Intrinsic::x86_sse_max_ss:
1709 case Intrinsic::x86_sse2_sub_sd:
1710 case Intrinsic::x86_sse2_mul_sd:
1711 case Intrinsic::x86_sse2_min_sd:
1712 case Intrinsic::x86_sse2_max_sd:
1713 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1714 UndefElts, Depth+1);
1715 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1716 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1717 UndefElts2, Depth+1);
1718 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1719
1720 // If only the low elt is demanded and this is a scalarizable intrinsic,
1721 // scalarize it now.
1722 if (DemandedElts == 1) {
1723 switch (II->getIntrinsicID()) {
1724 default: break;
1725 case Intrinsic::x86_sse_sub_ss:
1726 case Intrinsic::x86_sse_mul_ss:
1727 case Intrinsic::x86_sse2_sub_sd:
1728 case Intrinsic::x86_sse2_mul_sd:
1729 // TODO: Lower MIN/MAX/ABS/etc
1730 Value *LHS = II->getOperand(1);
1731 Value *RHS = II->getOperand(2);
1732 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001733 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001734 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001735 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001736 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001737
1738 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001739 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001740 case Intrinsic::x86_sse_sub_ss:
1741 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001742 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001743 II->getName()), *II);
1744 break;
1745 case Intrinsic::x86_sse_mul_ss:
1746 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001747 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001748 II->getName()), *II);
1749 break;
1750 }
1751
1752 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001753 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001754 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001755 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001756 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001757 return New;
1758 }
1759 }
1760
1761 // Output elements are undefined if both are undefined. Consider things
1762 // like undef&0. The result is known zero, not undef.
1763 UndefElts &= UndefElts2;
1764 break;
1765 }
1766 break;
1767 }
1768 }
1769 return MadeChange ? I : 0;
1770}
1771
Dan Gohman45b4e482008-05-19 22:14:15 +00001772
Chris Lattner564a7272003-08-13 19:01:45 +00001773/// AssociativeOpt - Perform an optimization on an associative operator. This
1774/// function is designed to check a chain of associative operators for a
1775/// potential to apply a certain optimization. Since the optimization may be
1776/// applicable if the expression was reassociated, this checks the chain, then
1777/// reassociates the expression as necessary to expose the optimization
1778/// opportunity. This makes use of a special Functor, which must define
1779/// 'shouldApply' and 'apply' methods.
1780///
1781template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001782static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001783 unsigned Opcode = Root.getOpcode();
1784 Value *LHS = Root.getOperand(0);
1785
1786 // Quick check, see if the immediate LHS matches...
1787 if (F.shouldApply(LHS))
1788 return F.apply(Root);
1789
1790 // Otherwise, if the LHS is not of the same opcode as the root, return.
1791 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001792 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001793 // Should we apply this transform to the RHS?
1794 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1795
1796 // If not to the RHS, check to see if we should apply to the LHS...
1797 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1798 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1799 ShouldApply = true;
1800 }
1801
1802 // If the functor wants to apply the optimization to the RHS of LHSI,
1803 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1804 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001805 // Now all of the instructions are in the current basic block, go ahead
1806 // and perform the reassociation.
1807 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1808
1809 // First move the selected RHS to the LHS of the root...
1810 Root.setOperand(0, LHSI->getOperand(1));
1811
1812 // Make what used to be the LHS of the root be the user of the root...
1813 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001814 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001815 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001816 return 0;
1817 }
Chris Lattner65725312004-04-16 18:08:07 +00001818 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001819 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001820 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001821 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001822 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001823
1824 // Now propagate the ExtraOperand down the chain of instructions until we
1825 // get to LHSI.
1826 while (TmpLHSI != LHSI) {
1827 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001828 // Move the instruction to immediately before the chain we are
1829 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001830 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001831 ARI = NextLHSI;
1832
Chris Lattner564a7272003-08-13 19:01:45 +00001833 Value *NextOp = NextLHSI->getOperand(1);
1834 NextLHSI->setOperand(1, ExtraOperand);
1835 TmpLHSI = NextLHSI;
1836 ExtraOperand = NextOp;
1837 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001838
Chris Lattner564a7272003-08-13 19:01:45 +00001839 // Now that the instructions are reassociated, have the functor perform
1840 // the transformation...
1841 return F.apply(Root);
1842 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001843
Chris Lattner564a7272003-08-13 19:01:45 +00001844 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1845 }
1846 return 0;
1847}
1848
Dan Gohman844731a2008-05-13 00:00:25 +00001849namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001850
Nick Lewycky02d639f2008-05-23 04:34:58 +00001851// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001852struct AddRHS {
1853 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001854 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001855 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1856 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001857 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001858 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001859 }
1860};
1861
1862// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1863// iff C1&C2 == 0
1864struct AddMaskingAnd {
1865 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001866 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001867 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001868 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001869 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001870 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001871 }
1872 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001873 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001874 }
1875};
1876
Dan Gohman844731a2008-05-13 00:00:25 +00001877}
1878
Chris Lattner6e7ba452005-01-01 16:22:27 +00001879static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001880 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001881 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001882 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001883 }
1884
Chris Lattner2eefe512004-04-09 19:05:30 +00001885 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001886 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1887 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001888
Chris Lattner2eefe512004-04-09 19:05:30 +00001889 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1890 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001891 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1892 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001893 }
1894
1895 Value *Op0 = SO, *Op1 = ConstOperand;
1896 if (!ConstIsRHS)
1897 std::swap(Op0, Op1);
1898 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001899 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001900 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001901 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001902 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +00001903 Op0, Op1, SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001904 else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001905 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001906 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001907 return IC->InsertNewInstBefore(New, I);
1908}
1909
1910// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1911// constant as the other operand, try to fold the binary operator into the
1912// select arguments. This also works for Cast instructions, which obviously do
1913// not have a second operand.
1914static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1915 InstCombiner *IC) {
1916 // Don't modify shared select instructions
1917 if (!SI->hasOneUse()) return 0;
1918 Value *TV = SI->getOperand(1);
1919 Value *FV = SI->getOperand(2);
1920
1921 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001922 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00001923 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001924
Chris Lattner6e7ba452005-01-01 16:22:27 +00001925 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1926 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1927
Gabor Greif051a9502008-04-06 20:25:17 +00001928 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1929 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001930 }
1931 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001932}
1933
Chris Lattner4e998b22004-09-29 05:07:12 +00001934
1935/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1936/// node as operand #0, see if we can fold the instruction into the PHI (which
1937/// is only possible if all operands to the PHI are constants).
1938Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1939 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001940 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001941 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001942
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001943 // Check to see if all of the operands of the PHI are constants. If there is
1944 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001945 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001946 BasicBlock *NonConstBB = 0;
1947 for (unsigned i = 0; i != NumPHIValues; ++i)
1948 if (!isa<Constant>(PN->getIncomingValue(i))) {
1949 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001950 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001951 NonConstBB = PN->getIncomingBlock(i);
1952
1953 // If the incoming non-constant value is in I's block, we have an infinite
1954 // loop.
1955 if (NonConstBB == I.getParent())
1956 return 0;
1957 }
1958
1959 // If there is exactly one non-constant value, we can insert a copy of the
1960 // operation in that block. However, if this is a critical edge, we would be
1961 // inserting the computation one some other paths (e.g. inside a loop). Only
1962 // do this if the pred block is unconditionally branching into the phi block.
1963 if (NonConstBB) {
1964 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1965 if (!BI || !BI->isUnconditional()) return 0;
1966 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001967
1968 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001969 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001970 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001971 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001972 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001973
1974 // Next, add all of the operands to the PHI.
1975 if (I.getNumOperands() == 2) {
1976 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001977 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001978 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001979 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001980 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001981 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001982 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001983 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001984 } else {
1985 assert(PN->getIncomingBlock(i) == NonConstBB);
1986 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001987 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001988 PN->getIncomingValue(i), C, "phitmp",
1989 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001990 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001991 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001992 CI->getPredicate(),
1993 PN->getIncomingValue(i), C, "phitmp",
1994 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001995 else
Torok Edwinc23197a2009-07-14 16:55:14 +00001996 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001997
Chris Lattner7a1e9242009-08-30 06:13:40 +00001998 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001999 }
2000 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002001 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002002 } else {
2003 CastInst *CI = cast<CastInst>(&I);
2004 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002005 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002006 Value *InV;
2007 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002008 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002009 } else {
2010 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002011 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002012 I.getType(), "phitmp",
2013 NonConstBB->getTerminator());
Chris Lattner7a1e9242009-08-30 06:13:40 +00002014 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002015 }
2016 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002017 }
2018 }
2019 return ReplaceInstUsesWith(I, NewPN);
2020}
2021
Chris Lattner2454a2e2008-01-29 06:52:45 +00002022
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002023/// WillNotOverflowSignedAdd - Return true if we can prove that:
2024/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2025/// This basically requires proving that the add in the original type would not
2026/// overflow to change the sign bit or have a carry out.
2027bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2028 // There are different heuristics we can use for this. Here are some simple
2029 // ones.
2030
2031 // Add has the property that adding any two 2's complement numbers can only
2032 // have one carry bit which can change a sign. As such, if LHS and RHS each
2033 // have at least two sign bits, we know that the addition of the two values will
2034 // sign extend fine.
2035 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2036 return true;
2037
2038
2039 // If one of the operands only has one non-zero bit, and if the other operand
2040 // has a known-zero bit in a more significant place than it (not including the
2041 // sign bit) the ripple may go up to and fill the zero, but won't change the
2042 // sign. For example, (X & ~4) + 1.
2043
2044 // TODO: Implement.
2045
2046 return false;
2047}
2048
Chris Lattner2454a2e2008-01-29 06:52:45 +00002049
Chris Lattner7e708292002-06-25 16:13:24 +00002050Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002051 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002052 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002053
Chris Lattner66331a42004-04-10 22:01:55 +00002054 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002055 // X + undef -> undef
2056 if (isa<UndefValue>(RHS))
2057 return ReplaceInstUsesWith(I, RHS);
2058
Chris Lattner66331a42004-04-10 22:01:55 +00002059 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002060 if (RHSC->isNullValue())
2061 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002062
Chris Lattner66331a42004-04-10 22:01:55 +00002063 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002064 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002065 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002066 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002067 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002068 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002069
2070 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2071 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002072 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002073 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002074
Eli Friedman709b33d2009-07-13 22:27:52 +00002075 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002076 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002077 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002078 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002079 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002080
2081 if (isa<PHINode>(LHS))
2082 if (Instruction *NV = FoldOpIntoPhi(I))
2083 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002084
Chris Lattner4f637d42006-01-06 17:59:59 +00002085 ConstantInt *XorRHS = 0;
2086 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002087 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002088 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002089 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002090 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002091
Zhou Sheng4351c642007-04-02 08:20:41 +00002092 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002093 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2094 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002095 do {
2096 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002097 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2098 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002099 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2100 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002101 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002102 if (!MaskedValueIsZero(XorLHS,
2103 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002104 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002105 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002106 }
2107 }
2108 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002109 C0080Val = APIntOps::lshr(C0080Val, Size);
2110 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2111 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002112
Reid Spencer35c38852007-03-28 01:36:16 +00002113 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002114 // with funny bit widths then this switch statement should be removed. It
2115 // is just here to get the size of the "middle" type back up to something
2116 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002117 const Type *MiddleType = 0;
2118 switch (Size) {
2119 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002120 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2121 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2122 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002123 }
2124 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002125 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002126 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002127 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002128 }
2129 }
Chris Lattner66331a42004-04-10 22:01:55 +00002130 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002131
Owen Anderson1d0be152009-08-13 21:58:54 +00002132 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002133 return BinaryOperator::CreateXor(LHS, RHS);
2134
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002135 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002136 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002137 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002138 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002139
2140 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2141 if (RHSI->getOpcode() == Instruction::Sub)
2142 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2143 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2144 }
2145 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2146 if (LHSI->getOpcode() == Instruction::Sub)
2147 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2148 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2149 }
Robert Bocchino71698282004-07-27 21:02:21 +00002150 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002151
Chris Lattner5c4afb92002-05-08 22:46:53 +00002152 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002153 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002154 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002155 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002156 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002157 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002158 InsertNewInstBefore(NewAdd, I);
Dan Gohman4ae51262009-08-12 16:23:25 +00002159 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002160 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002161 }
2162
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002163 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002164 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002165
2166 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002167 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002168 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002169 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002170
Misha Brukmanfd939082005-04-21 23:48:37 +00002171
Chris Lattner50af16a2004-11-13 19:50:12 +00002172 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002173 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002174 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002175 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002176
2177 // X*C1 + X*C2 --> X * (C1+C2)
2178 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002179 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002180 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002181 }
2182
2183 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002184 if (dyn_castFoldableMul(RHS, C2) == LHS)
2185 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002186
Chris Lattnere617c9e2007-01-05 02:17:46 +00002187 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002188 if (dyn_castNotVal(LHS) == RHS ||
2189 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002190 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002191
Chris Lattnerad3448c2003-02-18 19:57:07 +00002192
Chris Lattner564a7272003-08-13 19:01:45 +00002193 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002194 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2195 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002196 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002197
2198 // A+B --> A|B iff A and B have no bits set in common.
2199 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2200 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2201 APInt LHSKnownOne(IT->getBitWidth(), 0);
2202 APInt LHSKnownZero(IT->getBitWidth(), 0);
2203 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2204 if (LHSKnownZero != 0) {
2205 APInt RHSKnownOne(IT->getBitWidth(), 0);
2206 APInt RHSKnownZero(IT->getBitWidth(), 0);
2207 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2208
2209 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002210 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002211 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002212 }
2213 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002214
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002215 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002216 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002217 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002218 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2219 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002220 if (W != Y) {
2221 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002222 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002223 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002224 std::swap(W, X);
2225 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002226 std::swap(Y, Z);
2227 std::swap(W, X);
2228 }
2229 }
2230
2231 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002232 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002233 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002234 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002235 }
2236 }
2237 }
2238
Chris Lattner6b032052003-10-02 15:11:26 +00002239 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002240 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002241 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002242 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002243
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002244 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002245 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002246 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002247 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002248 if (Anded == CRHS) {
2249 // See if all bits from the first bit set in the Add RHS up are included
2250 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002251 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002252
2253 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002254 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002255
2256 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002257 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002258
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002259 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2260 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002261 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002262 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002263 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002264 }
2265 }
2266 }
2267
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002268 // Try to fold constant add into select arguments.
2269 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002270 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002271 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002272 }
2273
Chris Lattner42790482007-12-20 01:56:58 +00002274 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002275 {
2276 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002277 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002278 if (!SI) {
2279 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002280 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002281 }
Chris Lattner42790482007-12-20 01:56:58 +00002282 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002283 Value *TV = SI->getTrueValue();
2284 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002285 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002286
2287 // Can we fold the add into the argument of the select?
2288 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002289 if (match(FV, m_Zero()) &&
2290 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002291 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002292 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002293 if (match(TV, m_Zero()) &&
2294 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002295 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002296 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002297 }
2298 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002299
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002300 // Check for (add (sext x), y), see if we can merge this into an
2301 // integer add followed by a sext.
2302 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2303 // (add (sext x), cst) --> (sext (add x, cst'))
2304 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2305 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002306 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002307 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002308 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002309 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2310 // Insert the new, smaller add.
2311 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2312 CI, "addconv");
2313 InsertNewInstBefore(NewAdd, I);
2314 return new SExtInst(NewAdd, I.getType());
2315 }
2316 }
2317
2318 // (add (sext x), (sext y)) --> (sext (add int x, y))
2319 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2320 // Only do this if x/y have the same type, if at last one of them has a
2321 // single use (so we don't increase the number of sexts), and if the
2322 // integer add will not overflow.
2323 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2324 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2325 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2326 RHSConv->getOperand(0))) {
2327 // Insert the new integer add.
2328 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2329 RHSConv->getOperand(0),
2330 "addconv");
2331 InsertNewInstBefore(NewAdd, I);
2332 return new SExtInst(NewAdd, I.getType());
2333 }
2334 }
2335 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002336
2337 return Changed ? &I : 0;
2338}
2339
2340Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2341 bool Changed = SimplifyCommutative(I);
2342 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2343
2344 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2345 // X + 0 --> X
2346 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002347 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002348 (I.getType())->getValueAPF()))
2349 return ReplaceInstUsesWith(I, LHS);
2350 }
2351
2352 if (isa<PHINode>(LHS))
2353 if (Instruction *NV = FoldOpIntoPhi(I))
2354 return NV;
2355 }
2356
2357 // -A + B --> B - A
2358 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002359 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002360 return BinaryOperator::CreateFSub(RHS, LHSV);
2361
2362 // A + -B --> A - B
2363 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002364 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002365 return BinaryOperator::CreateFSub(LHS, V);
2366
2367 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2368 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2369 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2370 return ReplaceInstUsesWith(I, LHS);
2371
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002372 // Check for (add double (sitofp x), y), see if we can merge this into an
2373 // integer add followed by a promotion.
2374 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2375 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2376 // ... if the constant fits in the integer value. This is useful for things
2377 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2378 // requires a constant pool load, and generally allows the add to be better
2379 // instcombined.
2380 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2381 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002382 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002383 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002384 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002385 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2386 // Insert the new integer add.
2387 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2388 CI, "addconv");
2389 InsertNewInstBefore(NewAdd, I);
2390 return new SIToFPInst(NewAdd, I.getType());
2391 }
2392 }
2393
2394 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2395 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2396 // Only do this if x/y have the same type, if at last one of them has a
2397 // single use (so we don't increase the number of int->fp conversions),
2398 // and if the integer add will not overflow.
2399 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2400 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2401 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2402 RHSConv->getOperand(0))) {
2403 // Insert the new integer add.
2404 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2405 RHSConv->getOperand(0),
2406 "addconv");
2407 InsertNewInstBefore(NewAdd, I);
2408 return new SIToFPInst(NewAdd, I.getType());
2409 }
2410 }
2411 }
2412
Chris Lattner7e708292002-06-25 16:13:24 +00002413 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002414}
2415
Chris Lattner7e708292002-06-25 16:13:24 +00002416Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002417 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002418
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002419 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002420 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002421
Chris Lattner233f7dc2002-08-12 21:17:25 +00002422 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002423 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002424 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002425
Chris Lattnere87597f2004-10-16 18:11:37 +00002426 if (isa<UndefValue>(Op0))
2427 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2428 if (isa<UndefValue>(Op1))
2429 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2430
Chris Lattnerd65460f2003-11-05 01:06:05 +00002431 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2432 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002433 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002434 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002435
Chris Lattnerd65460f2003-11-05 01:06:05 +00002436 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002437 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002438 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002439 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002440
Chris Lattner76b7a062007-01-15 07:02:54 +00002441 // -(X >>u 31) -> (X >>s 31)
2442 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002443 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002444 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002445 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002446 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002447 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002448 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002449 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002450 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002451 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002452 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002453 }
2454 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002455 }
2456 else if (SI->getOpcode() == Instruction::AShr) {
2457 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2458 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002459 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002460 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002461 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002462 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002463 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002464 }
2465 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002466 }
2467 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002468 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002469
2470 // Try to fold constant sub into select arguments.
2471 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002472 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002473 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002474
2475 // C - zext(bool) -> bool ? C - 1 : C
2476 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002477 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002478 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002479 }
2480
Owen Anderson1d0be152009-08-13 21:58:54 +00002481 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002482 return BinaryOperator::CreateXor(Op0, Op1);
2483
Chris Lattner43d84d62005-04-07 16:15:25 +00002484 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002485 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002486 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002487 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002488 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002489 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002490 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002491 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002492 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2493 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2494 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002495 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002496 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002497 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002498 }
2499
Chris Lattnerfd059242003-10-15 16:48:29 +00002500 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002501 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2502 // is not used by anyone else...
2503 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002504 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002505 // Swap the two operands of the subexpr...
2506 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2507 Op1I->setOperand(0, IIOp1);
2508 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002509
Chris Lattnera2881962003-02-18 19:28:33 +00002510 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002511 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002512 }
2513
2514 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2515 //
2516 if (Op1I->getOpcode() == Instruction::And &&
2517 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2518 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2519
Chris Lattnerf523d062004-06-09 05:08:07 +00002520 Value *NewNot =
Dan Gohman4ae51262009-08-12 16:23:25 +00002521 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002522 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002523 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002524
Reid Spencerac5209e2006-10-16 23:08:08 +00002525 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002526 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002527 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002528 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002529 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002530 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002531 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002532
Chris Lattnerad3448c2003-02-18 19:57:07 +00002533 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002534 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002535 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002536 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002537 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002538 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002539 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002540 }
Chris Lattner40371712002-05-09 01:29:19 +00002541 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002542 }
Chris Lattnera2881962003-02-18 19:28:33 +00002543
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002544 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2545 if (Op0I->getOpcode() == Instruction::Add) {
2546 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2547 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2548 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2549 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2550 } else if (Op0I->getOpcode() == Instruction::Sub) {
2551 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002552 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002553 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002554 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002555 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002556
Chris Lattner50af16a2004-11-13 19:50:12 +00002557 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002558 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002559 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002560 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002561
Chris Lattner50af16a2004-11-13 19:50:12 +00002562 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002563 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002564 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002565 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002566 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002567}
2568
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002569Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2570 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2571
2572 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002573 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002574 return BinaryOperator::CreateFAdd(Op0, V);
2575
2576 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2577 if (Op1I->getOpcode() == Instruction::FAdd) {
2578 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002579 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002580 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002581 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002582 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002583 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002584 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002585 }
2586
2587 return 0;
2588}
2589
Chris Lattnera0141b92007-07-15 20:42:37 +00002590/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2591/// comparison only checks the sign bit. If it only checks the sign bit, set
2592/// TrueIfSigned if the result of the comparison is true when the input value is
2593/// signed.
2594static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2595 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002596 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002597 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2598 TrueIfSigned = true;
2599 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002600 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2601 TrueIfSigned = true;
2602 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002603 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2604 TrueIfSigned = false;
2605 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002606 case ICmpInst::ICMP_UGT:
2607 // True if LHS u> RHS and RHS == high-bit-mask - 1
2608 TrueIfSigned = true;
2609 return RHS->getValue() ==
2610 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2611 case ICmpInst::ICMP_UGE:
2612 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2613 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002614 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002615 default:
2616 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002617 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002618}
2619
Chris Lattner7e708292002-06-25 16:13:24 +00002620Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002621 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002622 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002623
Eli Friedman1694e092009-07-18 09:12:15 +00002624 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002625 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002626
Chris Lattner233f7dc2002-08-12 21:17:25 +00002627 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002628 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2629 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002630
2631 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002632 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002633 if (SI->getOpcode() == Instruction::Shl)
2634 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002635 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002636 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002637
Zhou Sheng843f07672007-04-19 05:39:12 +00002638 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002639 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2640 if (CI->equalsInt(1)) // X * 1 == X
2641 return ReplaceInstUsesWith(I, Op0);
2642 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002643 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002644
Zhou Sheng97b52c22007-03-29 01:57:21 +00002645 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002646 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002647 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002648 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002649 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002650 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002651 if (Op1->isNullValue())
2652 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002653
2654 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2655 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002656 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002657
2658 // As above, vector X*splat(1.0) -> X in all defined cases.
2659 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002660 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2661 if (CI->equalsInt(1))
2662 return ReplaceInstUsesWith(I, Op0);
2663 }
2664 }
Chris Lattnera2881962003-02-18 19:28:33 +00002665 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002666
2667 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2668 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002669 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002670 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002671 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002672 Op1, "tmp");
2673 InsertNewInstBefore(Add, I);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002674 Value *C1C2 = ConstantExpr::getMul(Op1,
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002675 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002676 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002677
2678 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002679
2680 // Try to fold constant mul into select arguments.
2681 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002682 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002683 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002684
2685 if (isa<PHINode>(Op0))
2686 if (Instruction *NV = FoldOpIntoPhi(I))
2687 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002688 }
2689
Dan Gohman186a6362009-08-12 16:04:34 +00002690 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2691 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002692 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002693
Nick Lewycky0c730792008-11-21 07:33:58 +00002694 // (X / Y) * Y = X - (X % Y)
2695 // (X / Y) * -Y = (X % Y) - X
2696 {
2697 Value *Op1 = I.getOperand(1);
2698 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2699 if (!BO ||
2700 (BO->getOpcode() != Instruction::UDiv &&
2701 BO->getOpcode() != Instruction::SDiv)) {
2702 Op1 = Op0;
2703 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2704 }
Dan Gohman186a6362009-08-12 16:04:34 +00002705 Value *Neg = dyn_castNegVal(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002706 if (BO && BO->hasOneUse() &&
2707 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2708 (BO->getOpcode() == Instruction::UDiv ||
2709 BO->getOpcode() == Instruction::SDiv)) {
2710 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2711
Dan Gohmanfa94b942009-08-12 16:33:09 +00002712 // If the division is exact, X % Y is zero.
2713 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2714 if (SDiv->isExact()) {
2715 if (Op1BO == Op1)
2716 return ReplaceInstUsesWith(I, Op0BO);
2717 else
2718 return BinaryOperator::CreateNeg(Op0BO);
2719 }
2720
Nick Lewycky0c730792008-11-21 07:33:58 +00002721 Instruction *Rem;
2722 if (BO->getOpcode() == Instruction::UDiv)
2723 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2724 else
2725 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2726
2727 InsertNewInstBefore(Rem, I);
2728 Rem->takeName(BO);
2729
2730 if (Op1BO == Op1)
2731 return BinaryOperator::CreateSub(Op0BO, Rem);
2732 else
2733 return BinaryOperator::CreateSub(Rem, Op0BO);
2734 }
2735 }
2736
Owen Anderson1d0be152009-08-13 21:58:54 +00002737 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002738 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2739
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002740 // If one of the operands of the multiply is a cast from a boolean value, then
2741 // we know the bool is either zero or one, so this is a 'masking' multiply.
2742 // See if we can simplify things based on how the boolean was originally
2743 // formed.
2744 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002745 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Owen Anderson1d0be152009-08-13 21:58:54 +00002746 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002747 BoolCast = CI;
2748 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002749 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00002750 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002751 BoolCast = CI;
2752 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002753 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002754 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2755 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002756 bool TIS = false;
2757
Reid Spencere4d87aa2006-12-23 06:05:41 +00002758 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002759 // multiply into a shift/and combination.
2760 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002761 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2762 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002763 // Shift the X value right to turn it into "all signbits".
Owen Andersoneed707b2009-07-24 23:12:02 +00002764 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002765 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002766 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002767 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002768 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002769 BoolCast->getOperand(0)->getName()+
2770 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002771
2772 // If the multiply type is not the same as the source type, sign extend
2773 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002774 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002775 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2776 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002777 Instruction::CastOps opcode =
2778 (SrcBits == DstBits ? Instruction::BitCast :
2779 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2780 V = InsertCastBefore(opcode, V, I.getType(), I);
2781 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002782
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002783 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002784 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002785 }
2786 }
2787 }
2788
Chris Lattner7e708292002-06-25 16:13:24 +00002789 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002790}
2791
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002792Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2793 bool Changed = SimplifyCommutative(I);
2794 Value *Op0 = I.getOperand(0);
2795
2796 // Simplify mul instructions with a constant RHS...
2797 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2798 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2799 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2800 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2801 if (Op1F->isExactlyValue(1.0))
2802 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2803 } else if (isa<VectorType>(Op1->getType())) {
2804 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2805 // As above, vector X*splat(1.0) -> X in all defined cases.
2806 if (Constant *Splat = Op1V->getSplatValue()) {
2807 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2808 if (F->isExactlyValue(1.0))
2809 return ReplaceInstUsesWith(I, Op0);
2810 }
2811 }
2812 }
2813
2814 // Try to fold constant mul into select arguments.
2815 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2816 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2817 return R;
2818
2819 if (isa<PHINode>(Op0))
2820 if (Instruction *NV = FoldOpIntoPhi(I))
2821 return NV;
2822 }
2823
Dan Gohman186a6362009-08-12 16:04:34 +00002824 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2825 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002826 return BinaryOperator::CreateFMul(Op0v, Op1v);
2827
2828 return Changed ? &I : 0;
2829}
2830
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002831/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2832/// instruction.
2833bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2834 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2835
2836 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2837 int NonNullOperand = -1;
2838 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2839 if (ST->isNullValue())
2840 NonNullOperand = 2;
2841 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2842 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2843 if (ST->isNullValue())
2844 NonNullOperand = 1;
2845
2846 if (NonNullOperand == -1)
2847 return false;
2848
2849 Value *SelectCond = SI->getOperand(0);
2850
2851 // Change the div/rem to use 'Y' instead of the select.
2852 I.setOperand(1, SI->getOperand(NonNullOperand));
2853
2854 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2855 // problem. However, the select, or the condition of the select may have
2856 // multiple uses. Based on our knowledge that the operand must be non-zero,
2857 // propagate the known value for the select into other uses of it, and
2858 // propagate a known value of the condition into its other users.
2859
2860 // If the select and condition only have a single use, don't bother with this,
2861 // early exit.
2862 if (SI->use_empty() && SelectCond->hasOneUse())
2863 return true;
2864
2865 // Scan the current block backward, looking for other uses of SI.
2866 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2867
2868 while (BBI != BBFront) {
2869 --BBI;
2870 // If we found a call to a function, we can't assume it will return, so
2871 // information from below it cannot be propagated above it.
2872 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2873 break;
2874
2875 // Replace uses of the select or its condition with the known values.
2876 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2877 I != E; ++I) {
2878 if (*I == SI) {
2879 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002880 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002881 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002882 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2883 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002884 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002885 }
2886 }
2887
2888 // If we past the instruction, quit looking for it.
2889 if (&*BBI == SI)
2890 SI = 0;
2891 if (&*BBI == SelectCond)
2892 SelectCond = 0;
2893
2894 // If we ran out of things to eliminate, break out of the loop.
2895 if (SelectCond == 0 && SI == 0)
2896 break;
2897
2898 }
2899 return true;
2900}
2901
2902
Reid Spencer1628cec2006-10-26 06:15:43 +00002903/// This function implements the transforms on div instructions that work
2904/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2905/// used by the visitors to those instructions.
2906/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002907Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002908 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002909
Chris Lattner50b2ca42008-02-19 06:12:18 +00002910 // undef / X -> 0 for integer.
2911 // undef / X -> undef for FP (the undef could be a snan).
2912 if (isa<UndefValue>(Op0)) {
2913 if (Op0->getType()->isFPOrFPVector())
2914 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002915 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002916 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002917
2918 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002919 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002920 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002921
Reid Spencer1628cec2006-10-26 06:15:43 +00002922 return 0;
2923}
Misha Brukmanfd939082005-04-21 23:48:37 +00002924
Reid Spencer1628cec2006-10-26 06:15:43 +00002925/// This function implements the transforms common to both integer division
2926/// instructions (udiv and sdiv). It is called by the visitors to those integer
2927/// division instructions.
2928/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002929Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002930 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2931
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002932 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002933 if (Op0 == Op1) {
2934 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002935 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002936 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00002937 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002938 }
2939
Owen Andersoneed707b2009-07-24 23:12:02 +00002940 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002941 return ReplaceInstUsesWith(I, CI);
2942 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002943
Reid Spencer1628cec2006-10-26 06:15:43 +00002944 if (Instruction *Common = commonDivTransforms(I))
2945 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002946
2947 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2948 // This does not apply for fdiv.
2949 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2950 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002951
2952 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2953 // div X, 1 == X
2954 if (RHS->equalsInt(1))
2955 return ReplaceInstUsesWith(I, Op0);
2956
2957 // (X / C1) / C2 -> X / (C1*C2)
2958 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2959 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2960 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002961 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00002962 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00002963 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002964 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002965 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002966 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002967 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002968
Reid Spencerbca0e382007-03-23 20:05:17 +00002969 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002970 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2971 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2972 return R;
2973 if (isa<PHINode>(Op0))
2974 if (Instruction *NV = FoldOpIntoPhi(I))
2975 return NV;
2976 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002977 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002978
Chris Lattnera2881962003-02-18 19:28:33 +00002979 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002980 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002981 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00002982 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002983
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002984 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00002985 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002986 return ReplaceInstUsesWith(I, Op0);
2987
Nick Lewycky895f0852008-11-27 20:21:08 +00002988 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2989 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2990 // div X, 1 == X
2991 if (X->isOne())
2992 return ReplaceInstUsesWith(I, Op0);
2993 }
2994
Reid Spencer1628cec2006-10-26 06:15:43 +00002995 return 0;
2996}
2997
2998Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2999 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3000
3001 // Handle the integer div common cases
3002 if (Instruction *Common = commonIDivTransforms(I))
3003 return Common;
3004
Reid Spencer1628cec2006-10-26 06:15:43 +00003005 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003006 // X udiv C^2 -> X >> C
3007 // Check to see if this is an unsigned division with an exact power of 2,
3008 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003009 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003010 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003011 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003012
3013 // X udiv C, where C >= signbit
3014 if (C->getValue().isNegative()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003015 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky8ca52482008-11-27 22:41:10 +00003016 I);
Owen Andersona7235ea2009-07-31 20:28:14 +00003017 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003018 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003019 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003020 }
3021
3022 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003023 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003024 if (RHSI->getOpcode() == Instruction::Shl &&
3025 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003026 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003027 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003028 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003029 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003030 if (uint32_t C2 = C1.logBase2()) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003031 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003032 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003033 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003034 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003035 }
3036 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003037 }
3038
Reid Spencer1628cec2006-10-26 06:15:43 +00003039 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3040 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003041 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003042 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003043 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003044 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003045 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003046 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003047 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003048 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003049 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003050 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003051 Op0, TC, SI->getName()+".t");
3052 TSI = InsertNewInstBefore(TSI, I);
3053
3054 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003055 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003056 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003057 Op0, FC, SI->getName()+".f");
3058 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003059
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003060 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003061 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003062 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003063 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003064 return 0;
3065}
3066
Reid Spencer1628cec2006-10-26 06:15:43 +00003067Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3068 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3069
3070 // Handle the integer div common cases
3071 if (Instruction *Common = commonIDivTransforms(I))
3072 return Common;
3073
3074 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3075 // sdiv X, -1 == -X
3076 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003077 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003078
Dan Gohmanfa94b942009-08-12 16:33:09 +00003079 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003080 if (cast<SDivOperator>(&I)->isExact() &&
3081 RHS->getValue().isNonNegative() &&
3082 RHS->getValue().isPowerOf2()) {
3083 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3084 RHS->getValue().exactLogBase2());
3085 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3086 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003087
3088 // -X/C --> X/-C provided the negation doesn't overflow.
3089 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3090 if (isa<Constant>(Sub->getOperand(0)) &&
3091 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003092 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003093 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3094 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003095 }
3096
3097 // If the sign bits of both operands are zero (i.e. we can prove they are
3098 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003099 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003100 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003101 if (MaskedValueIsZero(Op0, Mask)) {
3102 if (MaskedValueIsZero(Op1, Mask)) {
3103 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3104 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3105 }
3106 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003107 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003108 ShiftedInt->getValue().isPowerOf2()) {
3109 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3110 // Safe because the only negative value (1 << Y) can take on is
3111 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3112 // the sign bit set.
3113 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3114 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003115 }
Eli Friedman8be17392009-07-18 09:53:21 +00003116 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003117
3118 return 0;
3119}
3120
3121Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3122 return commonDivTransforms(I);
3123}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003124
Reid Spencer0a783f72006-11-02 01:53:59 +00003125/// This function implements the transforms on rem instructions that work
3126/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3127/// is used by the visitors to those instructions.
3128/// @brief Transforms common to all three rem instructions
3129Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003130 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003131
Chris Lattner50b2ca42008-02-19 06:12:18 +00003132 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3133 if (I.getType()->isFPOrFPVector())
3134 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003135 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003136 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003137 if (isa<UndefValue>(Op1))
3138 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003139
3140 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003141 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3142 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003143
Reid Spencer0a783f72006-11-02 01:53:59 +00003144 return 0;
3145}
3146
3147/// This function implements the transforms common to both integer remainder
3148/// instructions (urem and srem). It is called by the visitors to those integer
3149/// remainder instructions.
3150/// @brief Common integer remainder transforms
3151Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3152 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3153
3154 if (Instruction *common = commonRemTransforms(I))
3155 return common;
3156
Dale Johannesened6af242009-01-21 00:35:19 +00003157 // 0 % X == 0 for integer, we don't need to preserve faults!
3158 if (Constant *LHS = dyn_cast<Constant>(Op0))
3159 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003160 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003161
Chris Lattner857e8cd2004-12-12 21:48:58 +00003162 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003163 // X % 0 == undef, we don't need to preserve faults!
3164 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003165 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003166
Chris Lattnera2881962003-02-18 19:28:33 +00003167 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003168 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003169
Chris Lattner97943922006-02-28 05:49:21 +00003170 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3171 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3172 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3173 return R;
3174 } else if (isa<PHINode>(Op0I)) {
3175 if (Instruction *NV = FoldOpIntoPhi(I))
3176 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003177 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003178
3179 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003180 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003181 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003182 }
Chris Lattnera2881962003-02-18 19:28:33 +00003183 }
3184
Reid Spencer0a783f72006-11-02 01:53:59 +00003185 return 0;
3186}
3187
3188Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3189 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3190
3191 if (Instruction *common = commonIRemTransforms(I))
3192 return common;
3193
3194 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3195 // X urem C^2 -> X and C
3196 // Check to see if this is an unsigned remainder with an exact power of 2,
3197 // if so, convert to a bitwise and.
3198 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003199 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003200 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003201 }
3202
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003203 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003204 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3205 if (RHSI->getOpcode() == Instruction::Shl &&
3206 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003207 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003208 Constant *N1 = Constant::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003209 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003210 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003211 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003212 }
3213 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003214 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003215
Reid Spencer0a783f72006-11-02 01:53:59 +00003216 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3217 // where C1&C2 are powers of two.
3218 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3219 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3220 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3221 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003222 if ((STO->getValue().isPowerOf2()) &&
3223 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003224 Value *TrueAnd = InsertNewInstBefore(
Dan Gohman186a6362009-08-12 16:04:34 +00003225 BinaryOperator::CreateAnd(Op0, SubOne(STO),
Owen Andersond672ecb2009-07-03 00:17:18 +00003226 SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003227 Value *FalseAnd = InsertNewInstBefore(
Dan Gohman186a6362009-08-12 16:04:34 +00003228 BinaryOperator::CreateAnd(Op0, SubOne(SFO),
Owen Andersond672ecb2009-07-03 00:17:18 +00003229 SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003230 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003231 }
3232 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003233 }
3234
Chris Lattner3f5b8772002-05-06 16:14:14 +00003235 return 0;
3236}
3237
Reid Spencer0a783f72006-11-02 01:53:59 +00003238Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3239 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3240
Dan Gohmancff55092007-11-05 23:16:33 +00003241 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003242 if (Instruction *common = commonIRemTransforms(I))
3243 return common;
3244
Dan Gohman186a6362009-08-12 16:04:34 +00003245 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003246 if (!isa<Constant>(RHSNeg) ||
3247 (isa<ConstantInt>(RHSNeg) &&
3248 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003249 // X % -Y -> X % Y
Chris Lattnerc3a3e362009-08-30 06:20:05 +00003250 AddOperandsToWorkList(I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003251 I.setOperand(1, RHSNeg);
3252 return &I;
3253 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003254
Dan Gohmancff55092007-11-05 23:16:33 +00003255 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003256 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003257 if (I.getType()->isInteger()) {
3258 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3259 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3260 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003261 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003262 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003263 }
3264
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003265 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003266 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3267 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003268
Nick Lewycky9dce8732008-12-20 16:48:00 +00003269 bool hasNegative = false;
3270 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3271 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3272 if (RHS->getValue().isNegative())
3273 hasNegative = true;
3274
3275 if (hasNegative) {
3276 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003277 for (unsigned i = 0; i != VWidth; ++i) {
3278 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3279 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003280 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003281 else
3282 Elts[i] = RHS;
3283 }
3284 }
3285
Owen Andersonaf7ec972009-07-28 21:19:26 +00003286 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003287 if (NewRHSV != RHSV) {
Chris Lattnerc3a3e362009-08-30 06:20:05 +00003288 AddOperandsToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003289 I.setOperand(1, NewRHSV);
3290 return &I;
3291 }
3292 }
3293 }
3294
Reid Spencer0a783f72006-11-02 01:53:59 +00003295 return 0;
3296}
3297
3298Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003299 return commonRemTransforms(I);
3300}
3301
Chris Lattner457dd822004-06-09 07:59:58 +00003302// isOneBitSet - Return true if there is exactly one bit set in the specified
3303// constant.
3304static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003305 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003306}
3307
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003308// isHighOnes - Return true if the constant is of the form 1+0+.
3309// This is the same as lowones(~X).
3310static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003311 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003312}
3313
Reid Spencere4d87aa2006-12-23 06:05:41 +00003314/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003315/// are carefully arranged to allow folding of expressions such as:
3316///
3317/// (A < B) | (A > B) --> (A != B)
3318///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003319/// Note that this is only valid if the first and second predicates have the
3320/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003321///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003322/// Three bits are used to represent the condition, as follows:
3323/// 0 A > B
3324/// 1 A == B
3325/// 2 A < B
3326///
3327/// <=> Value Definition
3328/// 000 0 Always false
3329/// 001 1 A > B
3330/// 010 2 A == B
3331/// 011 3 A >= B
3332/// 100 4 A < B
3333/// 101 5 A != B
3334/// 110 6 A <= B
3335/// 111 7 Always true
3336///
3337static unsigned getICmpCode(const ICmpInst *ICI) {
3338 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003339 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003340 case ICmpInst::ICMP_UGT: return 1; // 001
3341 case ICmpInst::ICMP_SGT: return 1; // 001
3342 case ICmpInst::ICMP_EQ: return 2; // 010
3343 case ICmpInst::ICMP_UGE: return 3; // 011
3344 case ICmpInst::ICMP_SGE: return 3; // 011
3345 case ICmpInst::ICMP_ULT: return 4; // 100
3346 case ICmpInst::ICMP_SLT: return 4; // 100
3347 case ICmpInst::ICMP_NE: return 5; // 101
3348 case ICmpInst::ICMP_ULE: return 6; // 110
3349 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003350 // True -> 7
3351 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003352 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003353 return 0;
3354 }
3355}
3356
Evan Cheng8db90722008-10-14 17:15:11 +00003357/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3358/// predicate into a three bit mask. It also returns whether it is an ordered
3359/// predicate by reference.
3360static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3361 isOrdered = false;
3362 switch (CC) {
3363 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3364 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003365 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3366 case FCmpInst::FCMP_UGT: return 1; // 001
3367 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3368 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003369 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3370 case FCmpInst::FCMP_UGE: return 3; // 011
3371 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3372 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003373 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3374 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003375 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3376 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003377 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003378 default:
3379 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003380 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003381 return 0;
3382 }
3383}
3384
Reid Spencere4d87aa2006-12-23 06:05:41 +00003385/// getICmpValue - This is the complement of getICmpCode, which turns an
3386/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003387/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003388/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003389static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003390 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003391 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003392 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003393 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003394 case 1:
3395 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003396 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003397 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003398 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3399 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003400 case 3:
3401 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003402 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003403 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003404 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003405 case 4:
3406 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003407 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003408 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003409 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3410 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003411 case 6:
3412 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003413 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003414 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003415 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003416 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003417 }
3418}
3419
Evan Cheng8db90722008-10-14 17:15:11 +00003420/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3421/// opcode and two operands into either a FCmp instruction. isordered is passed
3422/// in to determine which kind of predicate to use in the new fcmp instruction.
3423static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003424 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003425 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003426 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003427 case 0:
3428 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003429 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003430 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003431 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003432 case 1:
3433 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003434 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003435 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003436 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003437 case 2:
3438 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003439 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003440 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003441 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003442 case 3:
3443 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003444 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003445 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003446 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003447 case 4:
3448 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003449 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003450 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003451 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003452 case 5:
3453 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003454 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003455 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003456 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003457 case 6:
3458 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003459 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003460 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003461 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003462 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003463 }
3464}
3465
Chris Lattnerb9553d62008-11-16 04:55:20 +00003466/// PredicatesFoldable - Return true if both predicates match sign or if at
3467/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003468static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3469 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003470 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3471 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003472}
3473
3474namespace {
3475// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3476struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003477 InstCombiner &IC;
3478 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003479 ICmpInst::Predicate pred;
3480 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3481 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3482 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003483 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003484 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3485 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003486 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3487 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003488 return false;
3489 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003490 Instruction *apply(Instruction &Log) const {
3491 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3492 if (ICI->getOperand(0) != LHS) {
3493 assert(ICI->getOperand(1) == LHS);
3494 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003495 }
3496
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003497 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003498 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003499 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003500 unsigned Code;
3501 switch (Log.getOpcode()) {
3502 case Instruction::And: Code = LHSCode & RHSCode; break;
3503 case Instruction::Or: Code = LHSCode | RHSCode; break;
3504 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003505 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003506 }
3507
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003508 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3509 ICmpInst::isSignedPredicate(ICI->getPredicate());
3510
Owen Andersond672ecb2009-07-03 00:17:18 +00003511 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003512 if (Instruction *I = dyn_cast<Instruction>(RV))
3513 return I;
3514 // Otherwise, it's a constant boolean value...
3515 return IC.ReplaceInstUsesWith(Log, RV);
3516 }
3517};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003518} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003519
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003520// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3521// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003522// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003523Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003524 ConstantInt *OpRHS,
3525 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003526 BinaryOperator &TheAnd) {
3527 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003528 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003529 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003530 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003531
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003532 switch (Op->getOpcode()) {
3533 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003534 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003535 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003536 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003537 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003538 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003539 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003540 }
3541 break;
3542 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003543 if (Together == AndRHS) // (X | C) & C --> C
3544 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003545
Chris Lattner6e7ba452005-01-01 16:22:27 +00003546 if (Op->hasOneUse() && Together != OpRHS) {
3547 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003548 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003549 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003550 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003551 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003552 }
3553 break;
3554 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003555 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003556 // Adding a one to a single bit bit-field should be turned into an XOR
3557 // of the bit. First thing to check is to see if this AND is with a
3558 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003559 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003560
3561 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003562 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003563 // Ok, at this point, we know that we are masking the result of the
3564 // ADD down to exactly one bit. If the constant we are adding has
3565 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003566 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003567
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003568 // Check to see if any bits below the one bit set in AndRHSV are set.
3569 if ((AddRHS & (AndRHSV-1)) == 0) {
3570 // If not, the only thing that can effect the output of the AND is
3571 // the bit specified by AndRHSV. If that bit is set, the effect of
3572 // the XOR is to toggle the bit. If it is clear, then the ADD has
3573 // no effect.
3574 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3575 TheAnd.setOperand(0, X);
3576 return &TheAnd;
3577 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003578 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003579 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003580 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003581 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003582 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003583 }
3584 }
3585 }
3586 }
3587 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003588
3589 case Instruction::Shl: {
3590 // We know that the AND will not produce any of the bits shifted in, so if
3591 // the anded constant includes them, clear them now!
3592 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003593 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003594 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003595 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003596 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003597
Zhou Sheng290bec52007-03-29 08:15:12 +00003598 if (CI->getValue() == ShlMask) {
3599 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003600 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3601 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003602 TheAnd.setOperand(1, CI);
3603 return &TheAnd;
3604 }
3605 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003606 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003607 case Instruction::LShr:
3608 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003609 // We know that the AND will not produce any of the bits shifted in, so if
3610 // the anded constant includes them, clear them now! This only applies to
3611 // unsigned shifts, because a signed shr may bring in set bits!
3612 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003613 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003614 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003615 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003616 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003617
Zhou Sheng290bec52007-03-29 08:15:12 +00003618 if (CI->getValue() == ShrMask) {
3619 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003620 return ReplaceInstUsesWith(TheAnd, Op);
3621 } else if (CI != AndRHS) {
3622 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3623 return &TheAnd;
3624 }
3625 break;
3626 }
3627 case Instruction::AShr:
3628 // Signed shr.
3629 // See if this is shifting in some sign extension, then masking it out
3630 // with an and.
3631 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003632 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003633 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003634 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003635 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003636 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003637 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003638 // Make the argument unsigned.
3639 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003640 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003641 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003642 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003643 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003644 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003645 }
3646 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003647 }
3648 return 0;
3649}
3650
Chris Lattner8b170942002-08-09 23:47:40 +00003651
Chris Lattnera96879a2004-09-29 17:40:11 +00003652/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3653/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003654/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3655/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003656/// insert new instructions.
3657Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003658 bool isSigned, bool Inside,
3659 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003660 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003661 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003662 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003663
Chris Lattnera96879a2004-09-29 17:40:11 +00003664 if (Inside) {
3665 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003666 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003667
Reid Spencere4d87aa2006-12-23 06:05:41 +00003668 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003669 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003670 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003671 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003672 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003673 }
3674
3675 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003676 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003677 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003678 InsertNewInstBefore(Add, IB);
Owen Andersonbaf3c402009-07-29 18:55:55 +00003679 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003680 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003681 }
3682
3683 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003684 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003685
Reid Spencere4e40032007-03-21 23:19:50 +00003686 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003687 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003688 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003689 ICmpInst::Predicate pred = (isSigned ?
3690 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003691 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003692 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003693
Reid Spencere4e40032007-03-21 23:19:50 +00003694 // Emit V-Lo >u Hi-1-Lo
3695 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003696 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003697 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003698 InsertNewInstBefore(Add, IB);
Owen Andersonbaf3c402009-07-29 18:55:55 +00003699 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003700 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003701}
3702
Chris Lattner7203e152005-09-18 07:22:02 +00003703// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3704// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3705// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3706// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003707static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003708 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003709 uint32_t BitWidth = Val->getType()->getBitWidth();
3710 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003711
3712 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003713 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003714 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003715 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003716 return true;
3717}
3718
Chris Lattner7203e152005-09-18 07:22:02 +00003719/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3720/// where isSub determines whether the operator is a sub. If we can fold one of
3721/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003722///
3723/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3724/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3725/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3726///
3727/// return (A +/- B).
3728///
3729Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003730 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003731 Instruction &I) {
3732 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3733 if (!LHSI || LHSI->getNumOperands() != 2 ||
3734 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3735
3736 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3737
3738 switch (LHSI->getOpcode()) {
3739 default: return 0;
3740 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003741 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003742 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003743 if ((Mask->getValue().countLeadingZeros() +
3744 Mask->getValue().countPopulation()) ==
3745 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003746 break;
3747
3748 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3749 // part, we don't need any explicit masks to take them out of A. If that
3750 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003751 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003752 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003753 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003754 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003755 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003756 break;
3757 }
3758 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003759 return 0;
3760 case Instruction::Or:
3761 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003762 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003763 if ((Mask->getValue().countLeadingZeros() +
3764 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003765 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003766 break;
3767 return 0;
3768 }
3769
3770 Instruction *New;
3771 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003772 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003773 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003774 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003775 return InsertNewInstBefore(New, I);
3776}
3777
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003778/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3779Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3780 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003781 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003782 ConstantInt *LHSCst, *RHSCst;
3783 ICmpInst::Predicate LHSCC, RHSCC;
3784
Chris Lattnerea065fb2008-11-16 05:10:52 +00003785 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003786 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003787 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003788 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003789 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003790 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003791
3792 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3793 // where C is a power of 2
3794 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3795 LHSCst->getValue().isPowerOf2()) {
3796 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3797 InsertNewInstBefore(NewOr, I);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003798 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003799 }
3800
3801 // From here on, we only handle:
3802 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3803 if (Val != Val2) return 0;
3804
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003805 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3806 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3807 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3808 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3809 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3810 return 0;
3811
3812 // We can't fold (ugt x, C) & (sgt x, C2).
3813 if (!PredicatesFoldable(LHSCC, RHSCC))
3814 return 0;
3815
3816 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003817 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003818 if (ICmpInst::isSignedPredicate(LHSCC) ||
3819 (ICmpInst::isEquality(LHSCC) &&
3820 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003821 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003822 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003823 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3824
3825 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003826 std::swap(LHS, RHS);
3827 std::swap(LHSCst, RHSCst);
3828 std::swap(LHSCC, RHSCC);
3829 }
3830
3831 // At this point, we know we have have two icmp instructions
3832 // comparing a value against two constants and and'ing the result
3833 // together. Because of the above check, we know that we only have
3834 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3835 // (from the FoldICmpLogical check above), that the two constants
3836 // are not equal and that the larger constant is on the RHS
3837 assert(LHSCst != RHSCst && "Compares not folded above?");
3838
3839 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003840 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003841 case ICmpInst::ICMP_EQ:
3842 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003843 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003844 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3845 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3846 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003847 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003848 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3849 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3850 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3851 return ReplaceInstUsesWith(I, LHS);
3852 }
3853 case ICmpInst::ICMP_NE:
3854 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003855 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003856 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003857 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003858 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003859 break; // (X != 13 & X u< 15) -> no change
3860 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003861 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003862 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003863 break; // (X != 13 & X s< 15) -> no change
3864 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3865 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3866 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3867 return ReplaceInstUsesWith(I, RHS);
3868 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003869 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003870 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003871 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3872 Val->getName()+".off");
3873 InsertNewInstBefore(Add, I);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003874 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003875 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003876 }
3877 break; // (X != 13 & X != 15) -> no change
3878 }
3879 break;
3880 case ICmpInst::ICMP_ULT:
3881 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003882 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003883 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3884 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003885 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003886 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3887 break;
3888 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3889 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3890 return ReplaceInstUsesWith(I, LHS);
3891 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3892 break;
3893 }
3894 break;
3895 case ICmpInst::ICMP_SLT:
3896 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003897 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003898 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3899 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003900 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003901 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3902 break;
3903 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3904 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3905 return ReplaceInstUsesWith(I, LHS);
3906 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3907 break;
3908 }
3909 break;
3910 case ICmpInst::ICMP_UGT:
3911 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003912 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003913 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3914 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3915 return ReplaceInstUsesWith(I, RHS);
3916 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3917 break;
3918 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003919 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003920 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003921 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003922 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003923 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003924 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003925 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3926 break;
3927 }
3928 break;
3929 case ICmpInst::ICMP_SGT:
3930 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003931 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003932 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3933 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3934 return ReplaceInstUsesWith(I, RHS);
3935 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3936 break;
3937 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003938 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003939 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003940 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003941 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003942 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003943 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003944 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3945 break;
3946 }
3947 break;
3948 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003949
3950 return 0;
3951}
3952
Chris Lattner42d1be02009-07-23 05:14:02 +00003953Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3954 FCmpInst *RHS) {
3955
3956 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3957 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3958 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3959 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3960 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3961 // If either of the constants are nans, then the whole thing returns
3962 // false.
3963 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00003964 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003965 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00003966 LHS->getOperand(0), RHS->getOperand(0));
3967 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003968
3969 // Handle vector zeros. This occurs because the canonical form of
3970 // "fcmp ord x,x" is "fcmp ord x, 0".
3971 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3972 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003973 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00003974 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00003975 return 0;
3976 }
3977
3978 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3979 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3980 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3981
3982
3983 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3984 // Swap RHS operands to match LHS.
3985 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3986 std::swap(Op1LHS, Op1RHS);
3987 }
3988
3989 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3990 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3991 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003992 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00003993
3994 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00003995 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003996 if (Op0CC == FCmpInst::FCMP_TRUE)
3997 return ReplaceInstUsesWith(I, RHS);
3998 if (Op1CC == FCmpInst::FCMP_TRUE)
3999 return ReplaceInstUsesWith(I, LHS);
4000
4001 bool Op0Ordered;
4002 bool Op1Ordered;
4003 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4004 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4005 if (Op1Pred == 0) {
4006 std::swap(LHS, RHS);
4007 std::swap(Op0Pred, Op1Pred);
4008 std::swap(Op0Ordered, Op1Ordered);
4009 }
4010 if (Op0Pred == 0) {
4011 // uno && ueq -> uno && (uno || eq) -> ueq
4012 // ord && olt -> ord && (ord && lt) -> olt
4013 if (Op0Ordered == Op1Ordered)
4014 return ReplaceInstUsesWith(I, RHS);
4015
4016 // uno && oeq -> uno && (ord && eq) -> false
4017 // uno && ord -> false
4018 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004019 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004020 // ord && ueq -> ord && (uno || eq) -> oeq
4021 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4022 Op0LHS, Op0RHS, Context));
4023 }
4024 }
4025
4026 return 0;
4027}
4028
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004029
Chris Lattner7e708292002-06-25 16:13:24 +00004030Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004031 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004032 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004033
Chris Lattnere87597f2004-10-16 18:11:37 +00004034 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004035 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004036
Chris Lattner6e7ba452005-01-01 16:22:27 +00004037 // and X, X = X
4038 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004039 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004040
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004041 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004042 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004043 if (SimplifyDemandedInstructionBits(I))
4044 return &I;
4045 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004046 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004047 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004048 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004049 } else if (isa<ConstantAggregateZero>(Op1)) {
4050 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004051 }
4052 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004053
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004054 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004055 const APInt& AndRHSMask = AndRHS->getValue();
4056 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004057
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004058 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004059 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004060 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004061 Value *Op0LHS = Op0I->getOperand(0);
4062 Value *Op0RHS = Op0I->getOperand(1);
4063 switch (Op0I->getOpcode()) {
4064 case Instruction::Xor:
4065 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004066 // If the mask is only needed on one incoming arm, push it up.
4067 if (Op0I->hasOneUse()) {
4068 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4069 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004070 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004071 Op0RHS->getName()+".masked");
4072 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004073 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004074 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004075 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004076 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004077 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4078 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004079 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004080 Op0LHS->getName()+".masked");
4081 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004082 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004083 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4084 }
4085 }
4086
Chris Lattner6e7ba452005-01-01 16:22:27 +00004087 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004088 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004089 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4090 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4091 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4092 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004093 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004094 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004095 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004096 break;
4097
4098 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004099 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4100 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4101 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4102 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004103 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004104
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004105 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4106 // has 1's for all bits that the subtraction with A might affect.
4107 if (Op0I->hasOneUse()) {
4108 uint32_t BitWidth = AndRHSMask.getBitWidth();
4109 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4110 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4111
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004112 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004113 if (!(A && A->isZero()) && // avoid infinite recursion.
4114 MaskedValueIsZero(Op0LHS, Mask)) {
Dan Gohman4ae51262009-08-12 16:23:25 +00004115 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004116 InsertNewInstBefore(NewNeg, I);
4117 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4118 }
4119 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004120 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004121
4122 case Instruction::Shl:
4123 case Instruction::LShr:
4124 // (1 << x) & 1 --> zext(x == 0)
4125 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004126 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004127 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00004128 Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004129 InsertNewInstBefore(NewICmp, I);
4130 return new ZExtInst(NewICmp, I.getType());
4131 }
4132 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004133 }
4134
Chris Lattner58403262003-07-23 19:25:52 +00004135 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004136 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004137 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004138 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004139 // If this is an integer truncation or change from signed-to-unsigned, and
4140 // if the source is an and/or with immediate, transform it. This
4141 // frequently occurs for bitfield accesses.
4142 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004143 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004144 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004145 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004146 if (CastOp->getOpcode() == Instruction::And) {
4147 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004148 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4149 // This will fold the two constants together, which may allow
4150 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004151 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004152 CastOp->getOperand(0), I.getType(),
4153 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004154 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004155 // trunc_or_bitcast(C1)&C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004156 Constant *C3 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004157 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4158 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004159 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004160 } else if (CastOp->getOpcode() == Instruction::Or) {
4161 // Change: and (cast (or X, C1) to T), C2
4162 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004163 Constant *C3 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004164 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4165 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004166 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004167 return ReplaceInstUsesWith(I, AndRHS);
4168 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004169 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004170 }
Chris Lattner06782f82003-07-23 19:36:21 +00004171 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004172
4173 // Try to fold constant and into select arguments.
4174 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004175 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004176 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004177 if (isa<PHINode>(Op0))
4178 if (Instruction *NV = FoldOpIntoPhi(I))
4179 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004180 }
4181
Dan Gohman186a6362009-08-12 16:04:34 +00004182 Value *Op0NotVal = dyn_castNotVal(Op0);
4183 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004184
Chris Lattner5b62aa72004-06-18 06:07:51 +00004185 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004186 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004187
Misha Brukmancb6267b2004-07-30 12:50:08 +00004188 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004189 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004190 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004191 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004192 InsertNewInstBefore(Or, I);
Dan Gohman4ae51262009-08-12 16:23:25 +00004193 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004194 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004195
4196 {
Chris Lattner003b6202007-06-15 05:58:24 +00004197 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004198 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004199 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4200 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004201
4202 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004203 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004204 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004205 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004206 }
4207 }
4208
Dan Gohman4ae51262009-08-12 16:23:25 +00004209 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004210 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4211 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004212
4213 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004214 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004215 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004216 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004217 }
4218 }
Chris Lattner64daab52006-04-01 08:03:55 +00004219
4220 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004221 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004222 if (A == Op1) { // (A^B)&A -> A&(A^B)
4223 I.swapOperands(); // Simplify below
4224 std::swap(Op0, Op1);
4225 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4226 cast<BinaryOperator>(Op0)->swapOperands();
4227 I.swapOperands(); // Simplify below
4228 std::swap(Op0, Op1);
4229 }
4230 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004231
Chris Lattner64daab52006-04-01 08:03:55 +00004232 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004233 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004234 if (B == Op0) { // B&(A^B) -> B&(B^A)
4235 cast<BinaryOperator>(Op1)->swapOperands();
4236 std::swap(A, B);
4237 }
4238 if (A == Op0) { // A&(A^B) -> A & ~B
Dan Gohman4ae51262009-08-12 16:23:25 +00004239 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004240 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004241 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004242 }
4243 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004244
4245 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004246 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4247 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004248 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004249 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4250 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004251 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004252 }
4253
Reid Spencere4d87aa2006-12-23 06:05:41 +00004254 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4255 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004256 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004257 return R;
4258
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004259 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4260 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4261 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004262 }
4263
Chris Lattner6fc205f2006-05-05 06:39:07 +00004264 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004265 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4266 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4267 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4268 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004269 if (SrcTy == Op1C->getOperand(0)->getType() &&
4270 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004271 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004272 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4273 I.getType(), TD) &&
4274 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4275 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004276 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004277 Op1C->getOperand(0),
4278 I.getName());
4279 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004280 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004281 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004282 }
Chris Lattnere511b742006-11-14 07:46:50 +00004283
4284 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004285 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4286 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4287 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004288 SI0->getOperand(1) == SI1->getOperand(1) &&
4289 (SI0->hasOneUse() || SI1->hasOneUse())) {
4290 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004291 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004292 SI1->getOperand(0),
4293 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004294 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004295 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004296 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004297 }
4298
Evan Cheng8db90722008-10-14 17:15:11 +00004299 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004300 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004301 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4302 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4303 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004304 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004305
Chris Lattner7e708292002-06-25 16:13:24 +00004306 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004307}
4308
Chris Lattner8c34cd22008-10-05 02:13:19 +00004309/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4310/// capable of providing pieces of a bswap. The subexpression provides pieces
4311/// of a bswap if it is proven that each of the non-zero bytes in the output of
4312/// the expression came from the corresponding "byte swapped" byte in some other
4313/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4314/// we know that the expression deposits the low byte of %X into the high byte
4315/// of the bswap result and that all other bytes are zero. This expression is
4316/// accepted, the high byte of ByteValues is set to X to indicate a correct
4317/// match.
4318///
4319/// This function returns true if the match was unsuccessful and false if so.
4320/// On entry to the function the "OverallLeftShift" is a signed integer value
4321/// indicating the number of bytes that the subexpression is later shifted. For
4322/// example, if the expression is later right shifted by 16 bits, the
4323/// OverallLeftShift value would be -2 on entry. This is used to specify which
4324/// byte of ByteValues is actually being set.
4325///
4326/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4327/// byte is masked to zero by a user. For example, in (X & 255), X will be
4328/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4329/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4330/// always in the local (OverallLeftShift) coordinate space.
4331///
4332static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4333 SmallVector<Value*, 8> &ByteValues) {
4334 if (Instruction *I = dyn_cast<Instruction>(V)) {
4335 // If this is an or instruction, it may be an inner node of the bswap.
4336 if (I->getOpcode() == Instruction::Or) {
4337 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4338 ByteValues) ||
4339 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4340 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004341 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004342
4343 // If this is a logical shift by a constant multiple of 8, recurse with
4344 // OverallLeftShift and ByteMask adjusted.
4345 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4346 unsigned ShAmt =
4347 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4348 // Ensure the shift amount is defined and of a byte value.
4349 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4350 return true;
4351
4352 unsigned ByteShift = ShAmt >> 3;
4353 if (I->getOpcode() == Instruction::Shl) {
4354 // X << 2 -> collect(X, +2)
4355 OverallLeftShift += ByteShift;
4356 ByteMask >>= ByteShift;
4357 } else {
4358 // X >>u 2 -> collect(X, -2)
4359 OverallLeftShift -= ByteShift;
4360 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004361 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004362 }
4363
4364 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4365 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4366
4367 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4368 ByteValues);
4369 }
4370
4371 // If this is a logical 'and' with a mask that clears bytes, clear the
4372 // corresponding bytes in ByteMask.
4373 if (I->getOpcode() == Instruction::And &&
4374 isa<ConstantInt>(I->getOperand(1))) {
4375 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4376 unsigned NumBytes = ByteValues.size();
4377 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4378 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4379
4380 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4381 // If this byte is masked out by a later operation, we don't care what
4382 // the and mask is.
4383 if ((ByteMask & (1 << i)) == 0)
4384 continue;
4385
4386 // If the AndMask is all zeros for this byte, clear the bit.
4387 APInt MaskB = AndMask & Byte;
4388 if (MaskB == 0) {
4389 ByteMask &= ~(1U << i);
4390 continue;
4391 }
4392
4393 // If the AndMask is not all ones for this byte, it's not a bytezap.
4394 if (MaskB != Byte)
4395 return true;
4396
4397 // Otherwise, this byte is kept.
4398 }
4399
4400 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4401 ByteValues);
4402 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004403 }
4404
Chris Lattner8c34cd22008-10-05 02:13:19 +00004405 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4406 // the input value to the bswap. Some observations: 1) if more than one byte
4407 // is demanded from this input, then it could not be successfully assembled
4408 // into a byteswap. At least one of the two bytes would not be aligned with
4409 // their ultimate destination.
4410 if (!isPowerOf2_32(ByteMask)) return true;
4411 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004412
Chris Lattner8c34cd22008-10-05 02:13:19 +00004413 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4414 // is demanded, it needs to go into byte 0 of the result. This means that the
4415 // byte needs to be shifted until it lands in the right byte bucket. The
4416 // shift amount depends on the position: if the byte is coming from the high
4417 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4418 // low part, it must be shifted left.
4419 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4420 if (InputByteNo < ByteValues.size()/2) {
4421 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4422 return true;
4423 } else {
4424 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4425 return true;
4426 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004427
4428 // If the destination byte value is already defined, the values are or'd
4429 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004430 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004431 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004432 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004433 return false;
4434}
4435
4436/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4437/// If so, insert the new bswap intrinsic and return it.
4438Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004439 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004440 if (!ITy || ITy->getBitWidth() % 16 ||
4441 // ByteMask only allows up to 32-byte values.
4442 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004443 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004444
4445 /// ByteValues - For each byte of the result, we keep track of which value
4446 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004447 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004448 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004449
4450 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004451 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4452 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004453 return 0;
4454
4455 // Check to see if all of the bytes come from the same value.
4456 Value *V = ByteValues[0];
4457 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4458
4459 // Check to make sure that all of the bytes come from the same value.
4460 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4461 if (ByteValues[i] != V)
4462 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004463 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004464 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004465 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004466 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004467}
4468
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004469/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4470/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4471/// we can simplify this expression to "cond ? C : D or B".
4472static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004473 Value *C, Value *D,
4474 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004475 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004476 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004477 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004478 return 0;
4479
Chris Lattnera6a474d2008-11-16 04:26:55 +00004480 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004481 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004482 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004483 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004484 return SelectInst::Create(Cond, C, B);
4485 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004486 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004487 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004488 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004489 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004490 return 0;
4491}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004492
Chris Lattner69d4ced2008-11-16 05:20:07 +00004493/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4494Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4495 ICmpInst *LHS, ICmpInst *RHS) {
4496 Value *Val, *Val2;
4497 ConstantInt *LHSCst, *RHSCst;
4498 ICmpInst::Predicate LHSCC, RHSCC;
4499
4500 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004501 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004502 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004503 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004504 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004505 return 0;
4506
4507 // From here on, we only handle:
4508 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4509 if (Val != Val2) return 0;
4510
4511 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4512 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4513 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4514 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4515 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4516 return 0;
4517
4518 // We can't fold (ugt x, C) | (sgt x, C2).
4519 if (!PredicatesFoldable(LHSCC, RHSCC))
4520 return 0;
4521
4522 // Ensure that the larger constant is on the RHS.
4523 bool ShouldSwap;
4524 if (ICmpInst::isSignedPredicate(LHSCC) ||
4525 (ICmpInst::isEquality(LHSCC) &&
4526 ICmpInst::isSignedPredicate(RHSCC)))
4527 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4528 else
4529 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4530
4531 if (ShouldSwap) {
4532 std::swap(LHS, RHS);
4533 std::swap(LHSCst, RHSCst);
4534 std::swap(LHSCC, RHSCC);
4535 }
4536
4537 // At this point, we know we have have two icmp instructions
4538 // comparing a value against two constants and or'ing the result
4539 // together. Because of the above check, we know that we only have
4540 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4541 // FoldICmpLogical check above), that the two constants are not
4542 // equal.
4543 assert(LHSCst != RHSCst && "Compares not folded above?");
4544
4545 switch (LHSCC) {
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:
4548 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004549 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004550 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004551 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004552 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004553 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004554 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4555 Val->getName()+".off");
4556 InsertNewInstBefore(Add, I);
Dan Gohman186a6362009-08-12 16:04:34 +00004557 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004558 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004559 }
4560 break; // (X == 13 | X == 15) -> no change
4561 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4562 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4563 break;
4564 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4565 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4566 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4567 return ReplaceInstUsesWith(I, RHS);
4568 }
4569 break;
4570 case ICmpInst::ICMP_NE:
4571 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004572 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004573 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4574 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4575 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4576 return ReplaceInstUsesWith(I, LHS);
4577 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4578 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4579 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004580 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004581 }
4582 break;
4583 case ICmpInst::ICMP_ULT:
4584 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004585 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004586 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4587 break;
4588 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4589 // If RHSCst is [us]MAXINT, it is always false. Not handling
4590 // this can cause overflow.
4591 if (RHSCst->isMaxValue(false))
4592 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004593 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004594 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004595 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4596 break;
4597 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4598 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4599 return ReplaceInstUsesWith(I, RHS);
4600 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4601 break;
4602 }
4603 break;
4604 case ICmpInst::ICMP_SLT:
4605 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004606 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004607 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4608 break;
4609 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4610 // If RHSCst is [us]MAXINT, it is always false. Not handling
4611 // this can cause overflow.
4612 if (RHSCst->isMaxValue(true))
4613 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004614 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004615 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004616 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4617 break;
4618 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4619 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4620 return ReplaceInstUsesWith(I, RHS);
4621 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4622 break;
4623 }
4624 break;
4625 case ICmpInst::ICMP_UGT:
4626 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004627 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004628 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4629 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4630 return ReplaceInstUsesWith(I, LHS);
4631 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4632 break;
4633 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4634 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004635 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004636 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4637 break;
4638 }
4639 break;
4640 case ICmpInst::ICMP_SGT:
4641 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004642 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004643 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4644 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4645 return ReplaceInstUsesWith(I, LHS);
4646 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4647 break;
4648 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4649 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004650 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004651 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4652 break;
4653 }
4654 break;
4655 }
4656 return 0;
4657}
4658
Chris Lattner5414cc52009-07-23 05:46:22 +00004659Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4660 FCmpInst *RHS) {
4661 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4662 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4663 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4664 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4665 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4666 // If either of the constants are nans, then the whole thing returns
4667 // true.
4668 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004669 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004670
4671 // Otherwise, no need to compare the two constants, compare the
4672 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004673 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004674 LHS->getOperand(0), RHS->getOperand(0));
4675 }
4676
4677 // Handle vector zeros. This occurs because the canonical form of
4678 // "fcmp uno x,x" is "fcmp uno x, 0".
4679 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4680 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004681 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004682 LHS->getOperand(0), RHS->getOperand(0));
4683
4684 return 0;
4685 }
4686
4687 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4688 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4689 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4690
4691 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4692 // Swap RHS operands to match LHS.
4693 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4694 std::swap(Op1LHS, Op1RHS);
4695 }
4696 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4697 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4698 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004699 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004700 Op0LHS, Op0RHS);
4701 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004702 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004703 if (Op0CC == FCmpInst::FCMP_FALSE)
4704 return ReplaceInstUsesWith(I, RHS);
4705 if (Op1CC == FCmpInst::FCMP_FALSE)
4706 return ReplaceInstUsesWith(I, LHS);
4707 bool Op0Ordered;
4708 bool Op1Ordered;
4709 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4710 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4711 if (Op0Ordered == Op1Ordered) {
4712 // If both are ordered or unordered, return a new fcmp with
4713 // or'ed predicates.
4714 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4715 Op0LHS, Op0RHS, Context);
4716 if (Instruction *I = dyn_cast<Instruction>(RV))
4717 return I;
4718 // Otherwise, it's a constant boolean value...
4719 return ReplaceInstUsesWith(I, RV);
4720 }
4721 }
4722 return 0;
4723}
4724
Bill Wendlinga698a472008-12-01 08:23:25 +00004725/// FoldOrWithConstants - This helper function folds:
4726///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004727/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004728///
4729/// into:
4730///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004731/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004732///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004733/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004734Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004735 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004736 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4737 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004738
Bill Wendling286a0542008-12-02 06:24:20 +00004739 Value *V1 = 0;
4740 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004741 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004742
Bill Wendling29976b92008-12-02 06:18:11 +00004743 APInt Xor = CI1->getValue() ^ CI2->getValue();
4744 if (!Xor.isAllOnesValue()) return 0;
4745
Bill Wendling286a0542008-12-02 06:24:20 +00004746 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004747 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004748 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4749 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004750 }
4751
4752 return 0;
4753}
4754
Chris Lattner7e708292002-06-25 16:13:24 +00004755Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004756 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004757 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004758
Chris Lattner42593e62007-03-24 23:56:43 +00004759 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004760 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004761
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004762 // or X, X = X
4763 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004764 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004765
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004766 // See if we can simplify any instructions used by the instruction whose sole
4767 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004768 if (SimplifyDemandedInstructionBits(I))
4769 return &I;
4770 if (isa<VectorType>(I.getType())) {
4771 if (isa<ConstantAggregateZero>(Op1)) {
4772 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4773 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4774 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4775 return ReplaceInstUsesWith(I, I.getOperand(1));
4776 }
Chris Lattner42593e62007-03-24 23:56:43 +00004777 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004778
Chris Lattner3f5b8772002-05-06 16:14:14 +00004779 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004780 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004781 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004782 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004783 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004784 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004785 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004786 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004787 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004788 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004789 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004790 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004791
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004792 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004793 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004794 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004795 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004796 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004797 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004798 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004799 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004800 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004801
4802 // Try to fold constant and into select arguments.
4803 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004804 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004805 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004806 if (isa<PHINode>(Op0))
4807 if (Instruction *NV = FoldOpIntoPhi(I))
4808 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004809 }
4810
Chris Lattner4f637d42006-01-06 17:59:59 +00004811 Value *A = 0, *B = 0;
4812 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004813
Dan Gohman4ae51262009-08-12 16:23:25 +00004814 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004815 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4816 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004817 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004818 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4819 return ReplaceInstUsesWith(I, Op0);
4820
Chris Lattner6423d4c2006-07-10 20:25:24 +00004821 // (A | B) | C and A | (B | C) -> bswap if possible.
4822 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004823 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4824 match(Op1, m_Or(m_Value(), m_Value())) ||
4825 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4826 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004827 if (Instruction *BSwap = MatchBSwap(I))
4828 return BSwap;
4829 }
4830
Chris Lattner6e4c6492005-05-09 04:58:36 +00004831 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004832 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004833 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004834 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004835 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004836 InsertNewInstBefore(NOr, I);
4837 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004838 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004839 }
4840
4841 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004842 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004843 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004844 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004845 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004846 InsertNewInstBefore(NOr, I);
4847 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004848 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004849 }
4850
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004851 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004852 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004853 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4854 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004855 Value *V1 = 0, *V2 = 0, *V3 = 0;
4856 C1 = dyn_cast<ConstantInt>(C);
4857 C2 = dyn_cast<ConstantInt>(D);
4858 if (C1 && C2) { // (A & C1)|(B & C2)
4859 // If we have: ((V + N) & C1) | (V & C2)
4860 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4861 // replace with V+N.
4862 if (C1->getValue() == ~C2->getValue()) {
4863 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004864 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004865 // Add commutes, try both ways.
4866 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4867 return ReplaceInstUsesWith(I, A);
4868 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4869 return ReplaceInstUsesWith(I, A);
4870 }
4871 // Or commutes, try both ways.
4872 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004873 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004874 // Add commutes, try both ways.
4875 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4876 return ReplaceInstUsesWith(I, B);
4877 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4878 return ReplaceInstUsesWith(I, B);
4879 }
4880 }
Chris Lattner044e5332007-04-08 08:01:49 +00004881 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004882 }
4883
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004884 // Check to see if we have any common things being and'ed. If so, find the
4885 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004886 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4887 if (A == B) // (A & C)|(A & D) == A & (C|D)
4888 V1 = A, V2 = C, V3 = D;
4889 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4890 V1 = A, V2 = B, V3 = C;
4891 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4892 V1 = C, V2 = A, V3 = D;
4893 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4894 V1 = C, V2 = A, V3 = B;
4895
4896 if (V1) {
4897 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004898 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4899 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004900 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004901 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004902
Dan Gohman1975d032008-10-30 20:40:10 +00004903 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004904 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004905 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004906 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004907 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004908 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004909 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004910 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004911 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004912
Bill Wendlingb01865c2008-11-30 13:52:49 +00004913 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004914 if ((match(C, m_Not(m_Specific(D))) &&
4915 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004916 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004917 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004918 if ((match(A, m_Not(m_Specific(D))) &&
4919 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004920 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004921 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004922 if ((match(C, m_Not(m_Specific(B))) &&
4923 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004924 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004925 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004926 if ((match(A, m_Not(m_Specific(B))) &&
4927 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004928 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004929 }
Chris Lattnere511b742006-11-14 07:46:50 +00004930
4931 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004932 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4933 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4934 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004935 SI0->getOperand(1) == SI1->getOperand(1) &&
4936 (SI0->hasOneUse() || SI1->hasOneUse())) {
4937 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004938 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004939 SI1->getOperand(0),
4940 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004941 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004942 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004943 }
4944 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004945
Bill Wendlingb3833d12008-12-01 01:07:11 +00004946 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004947 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4948 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004949 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004950 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004951 }
4952 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004953 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4954 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004955 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004956 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004957 }
4958
Dan Gohman4ae51262009-08-12 16:23:25 +00004959 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004960 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004961 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004962 } else {
4963 A = 0;
4964 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004965 // Note, A is still live here!
Dan Gohman4ae51262009-08-12 16:23:25 +00004966 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004967 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004968 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004969
Misha Brukmancb6267b2004-07-30 12:50:08 +00004970 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004971 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004972 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004973 I.getName()+".demorgan"), I);
Dan Gohman4ae51262009-08-12 16:23:25 +00004974 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004975 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004976 }
Chris Lattnera2881962003-02-18 19:28:33 +00004977
Reid Spencere4d87aa2006-12-23 06:05:41 +00004978 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4979 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00004980 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004981 return R;
4982
Chris Lattner69d4ced2008-11-16 05:20:07 +00004983 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4984 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4985 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004986 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004987
4988 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004989 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004990 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004991 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004992 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4993 !isa<ICmpInst>(Op1C->getOperand(0))) {
4994 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004995 if (SrcTy == Op1C->getOperand(0)->getType() &&
4996 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00004997 // Only do this if the casts both really cause code to be
4998 // generated.
4999 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5000 I.getType(), TD) &&
5001 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5002 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005003 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00005004 Op1C->getOperand(0),
5005 I.getName());
5006 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005007 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005008 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005009 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005010 }
Chris Lattner99c65742007-10-24 05:38:08 +00005011 }
5012
5013
5014 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5015 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005016 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5017 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5018 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005019 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005020
Chris Lattner7e708292002-06-25 16:13:24 +00005021 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005022}
5023
Dan Gohman844731a2008-05-13 00:00:25 +00005024namespace {
5025
Chris Lattnerc317d392004-02-16 01:20:27 +00005026// XorSelf - Implements: X ^ X --> 0
5027struct XorSelf {
5028 Value *RHS;
5029 XorSelf(Value *rhs) : RHS(rhs) {}
5030 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5031 Instruction *apply(BinaryOperator &Xor) const {
5032 return &Xor;
5033 }
5034};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005035
Dan Gohman844731a2008-05-13 00:00:25 +00005036}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005037
Chris Lattner7e708292002-06-25 16:13:24 +00005038Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005039 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005040 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005041
Evan Chengd34af782008-03-25 20:07:13 +00005042 if (isa<UndefValue>(Op1)) {
5043 if (isa<UndefValue>(Op0))
5044 // Handle undef ^ undef -> 0 special case. This is a common
5045 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005046 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005047 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005048 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005049
Chris Lattnerc317d392004-02-16 01:20:27 +00005050 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005051 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005052 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005053 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005054 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005055
5056 // See if we can simplify any instructions used by the instruction whose sole
5057 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005058 if (SimplifyDemandedInstructionBits(I))
5059 return &I;
5060 if (isa<VectorType>(I.getType()))
5061 if (isa<ConstantAggregateZero>(Op1))
5062 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005063
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005064 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005065 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005066 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5067 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5068 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5069 if (Op0I->getOpcode() == Instruction::And ||
5070 Op0I->getOpcode() == Instruction::Or) {
Dan Gohman186a6362009-08-12 16:04:34 +00005071 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5072 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005073 Instruction *NotY =
Dan Gohman4ae51262009-08-12 16:23:25 +00005074 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005075 Op0I->getOperand(1)->getName()+".not");
5076 InsertNewInstBefore(NotY, I);
5077 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005078 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005079 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005080 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005081 }
5082 }
5083 }
5084 }
5085
5086
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005087 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson5defacc2009-07-31 17:39:07 +00005088 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005089 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005090 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005091 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005092 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005093
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005094 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005095 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005096 FCI->getOperand(0), FCI->getOperand(1));
5097 }
5098
Nick Lewycky517e1f52008-05-31 19:01:33 +00005099 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5100 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5101 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5102 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5103 Instruction::CastOps Opcode = Op0C->getOpcode();
5104 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005105 if (RHS == ConstantExpr::getCast(Opcode,
Owen Anderson5defacc2009-07-31 17:39:07 +00005106 ConstantInt::getTrue(*Context),
Nick Lewycky517e1f52008-05-31 19:01:33 +00005107 Op0C->getDestTy())) {
5108 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5109 CI->getOpcode(), CI->getInversePredicate(),
5110 CI->getOperand(0), CI->getOperand(1)), I);
5111 NewCI->takeName(CI);
5112 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5113 }
5114 }
5115 }
5116 }
5117 }
5118
Reid Spencere4d87aa2006-12-23 06:05:41 +00005119 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005120 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005121 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5122 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005123 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5124 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005125 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005126 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005127 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005128
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005129 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005130 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005131 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005132 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005133 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005134 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005135 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005136 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005137 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005138 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005139 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005140 Constant *C = ConstantInt::get(*Context,
5141 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005142 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005143
Chris Lattner7c4049c2004-01-12 19:35:11 +00005144 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005145 } else if (Op0I->getOpcode() == Instruction::Or) {
5146 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005147 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005148 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005149 // Anything in both C1 and C2 is known to be zero, remove it from
5150 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005151 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5152 NewRHS = ConstantExpr::getAnd(NewRHS,
5153 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005154 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005155 I.setOperand(0, Op0I->getOperand(0));
5156 I.setOperand(1, NewRHS);
5157 return &I;
5158 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005159 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005160 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005161 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005162
5163 // Try to fold constant and into select arguments.
5164 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005165 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005166 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005167 if (isa<PHINode>(Op0))
5168 if (Instruction *NV = FoldOpIntoPhi(I))
5169 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005170 }
5171
Dan Gohman186a6362009-08-12 16:04:34 +00005172 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005173 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005174 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005175
Dan Gohman186a6362009-08-12 16:04:34 +00005176 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005177 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005178 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005179
Chris Lattner318bf792007-03-18 22:51:34 +00005180
5181 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5182 if (Op1I) {
5183 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005184 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005185 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005186 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005187 I.swapOperands();
5188 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005189 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005190 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005191 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005192 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005193 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005194 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005195 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005196 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005197 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005198 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005199 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005200 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005201 std::swap(A, B);
5202 }
Chris Lattner318bf792007-03-18 22:51:34 +00005203 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005204 I.swapOperands(); // Simplified below.
5205 std::swap(Op0, Op1);
5206 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005207 }
Chris Lattner318bf792007-03-18 22:51:34 +00005208 }
5209
5210 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5211 if (Op0I) {
5212 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005213 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005214 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005215 if (A == Op1) // (B|A)^B == (A|B)^B
5216 std::swap(A, B);
5217 if (B == Op1) { // (A|B)^B == A & ~B
5218 Instruction *NotB =
Dan Gohman4ae51262009-08-12 16:23:25 +00005219 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005220 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005221 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005222 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005223 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005224 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005225 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005226 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005227 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005228 if (A == Op1) // (A&B)^A -> (B&A)^A
5229 std::swap(A, B);
5230 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005231 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005232 Instruction *N =
Dan Gohman4ae51262009-08-12 16:23:25 +00005233 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005234 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005235 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005236 }
Chris Lattner318bf792007-03-18 22:51:34 +00005237 }
5238
5239 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5240 if (Op0I && Op1I && Op0I->isShift() &&
5241 Op0I->getOpcode() == Op1I->getOpcode() &&
5242 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5243 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5244 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005245 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005246 Op1I->getOperand(0),
5247 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005248 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005249 Op1I->getOperand(1));
5250 }
5251
5252 if (Op0I && Op1I) {
5253 Value *A, *B, *C, *D;
5254 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005255 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5256 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005257 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005258 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005259 }
5260 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005261 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5262 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005263 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005264 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005265 }
5266
5267 // (A & B)^(C & D)
5268 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005269 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5270 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005271 // (X & Y)^(X & Y) -> (Y^Z) & X
5272 Value *X = 0, *Y = 0, *Z = 0;
5273 if (A == C)
5274 X = A, Y = B, Z = D;
5275 else if (A == D)
5276 X = A, Y = B, Z = C;
5277 else if (B == C)
5278 X = B, Y = A, Z = D;
5279 else if (B == D)
5280 X = B, Y = A, Z = C;
5281
5282 if (X) {
5283 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005284 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5285 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005286 }
5287 }
5288 }
5289
Reid Spencere4d87aa2006-12-23 06:05:41 +00005290 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5291 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005292 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005293 return R;
5294
Chris Lattner6fc205f2006-05-05 06:39:07 +00005295 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005296 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005297 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005298 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5299 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005300 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005301 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005302 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5303 I.getType(), TD) &&
5304 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5305 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005306 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005307 Op1C->getOperand(0),
5308 I.getName());
5309 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005310 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005311 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005312 }
Chris Lattner99c65742007-10-24 05:38:08 +00005313 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005314
Chris Lattner7e708292002-06-25 16:13:24 +00005315 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005316}
5317
Owen Andersond672ecb2009-07-03 00:17:18 +00005318static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005319 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005320 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005321}
Chris Lattnera96879a2004-09-29 17:40:11 +00005322
Dan Gohman6de29f82009-06-15 22:12:54 +00005323static bool HasAddOverflow(ConstantInt *Result,
5324 ConstantInt *In1, ConstantInt *In2,
5325 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005326 if (IsSigned)
5327 if (In2->getValue().isNegative())
5328 return Result->getValue().sgt(In1->getValue());
5329 else
5330 return Result->getValue().slt(In1->getValue());
5331 else
5332 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005333}
5334
Dan Gohman6de29f82009-06-15 22:12:54 +00005335/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005336/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005337static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005338 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005339 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005340 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005341
Dan Gohman6de29f82009-06-15 22:12:54 +00005342 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5343 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005344 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005345 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5346 ExtractElement(In1, Idx, Context),
5347 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005348 IsSigned))
5349 return true;
5350 }
5351 return false;
5352 }
5353
5354 return HasAddOverflow(cast<ConstantInt>(Result),
5355 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5356 IsSigned);
5357}
5358
5359static bool HasSubOverflow(ConstantInt *Result,
5360 ConstantInt *In1, ConstantInt *In2,
5361 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005362 if (IsSigned)
5363 if (In2->getValue().isNegative())
5364 return Result->getValue().slt(In1->getValue());
5365 else
5366 return Result->getValue().sgt(In1->getValue());
5367 else
5368 return Result->getValue().ugt(In1->getValue());
5369}
5370
Dan Gohman6de29f82009-06-15 22:12:54 +00005371/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5372/// overflowed for this type.
5373static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005374 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005375 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005376 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005377
5378 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5379 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005380 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005381 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5382 ExtractElement(In1, Idx, Context),
5383 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005384 IsSigned))
5385 return true;
5386 }
5387 return false;
5388 }
5389
5390 return HasSubOverflow(cast<ConstantInt>(Result),
5391 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5392 IsSigned);
5393}
5394
Chris Lattner574da9b2005-01-13 20:14:25 +00005395/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5396/// code necessary to compute the offset from the base pointer (without adding
5397/// in the base pointer). Return the result as a signed integer of intptr size.
5398static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005399 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005400 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson1d0be152009-08-13 21:58:54 +00005401 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Anderson07cf79e2009-07-06 23:00:19 +00005402 LLVMContext *Context = IC.getContext();
Owen Andersona7235ea2009-07-31 20:28:14 +00005403 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005404
5405 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005406 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005407 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005408
Gabor Greif177dd3f2008-06-12 21:37:33 +00005409 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5410 ++i, ++GTI) {
5411 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005412 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005413 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5414 if (OpC->isZero()) continue;
5415
5416 // Handle a struct index, which adds its field offset to the pointer.
5417 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5418 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5419
5420 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005421 Result =
Owen Andersoneed707b2009-07-24 23:12:02 +00005422 ConstantInt::get(*Context,
5423 RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005424 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005425 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005426 BinaryOperator::CreateAdd(Result,
Owen Andersoneed707b2009-07-24 23:12:02 +00005427 ConstantInt::get(IntPtrTy, Size),
Chris Lattnere62f0212007-04-28 04:52:43 +00005428 GEP->getName()+".offs"), I);
5429 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005430 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005431
Owen Andersoneed707b2009-07-24 23:12:02 +00005432 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005433 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005434 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5435 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005436 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005437 Result = ConstantExpr::getAdd(RC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005438 else {
5439 // Emit an add instruction.
5440 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005441 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005442 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005443 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005444 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005445 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005446 // Convert to correct type.
5447 if (Op->getType() != IntPtrTy) {
5448 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005449 Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005450 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005451 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5452 true,
5453 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005454 }
5455 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005456 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattnere62f0212007-04-28 04:52:43 +00005457 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005458 Op = ConstantExpr::getMul(OpC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005459 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005460 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005461 GEP->getName()+".idx"), I);
5462 }
5463
5464 // Emit an add instruction.
5465 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00005466 Result = ConstantExpr::getAdd(cast<Constant>(Op),
Chris Lattnere62f0212007-04-28 04:52:43 +00005467 cast<Constant>(Result));
5468 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005469 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005470 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005471 }
5472 return Result;
5473}
5474
Chris Lattner10c0d912008-04-22 02:53:33 +00005475
Dan Gohman8f080f02009-07-17 22:16:21 +00005476/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5477/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5478/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5479/// be complex, and scales are involved. The above expression would also be
5480/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5481/// This later form is less amenable to optimization though, and we are allowed
5482/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005483///
5484/// If we can't emit an optimized form for this expression, this returns null.
5485///
5486static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5487 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005488 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005489 gep_type_iterator GTI = gep_type_begin(GEP);
5490
5491 // Check to see if this gep only has a single variable index. If so, and if
5492 // any constant indices are a multiple of its scale, then we can compute this
5493 // in terms of the scale of the variable index. For example, if the GEP
5494 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5495 // because the expression will cross zero at the same point.
5496 unsigned i, e = GEP->getNumOperands();
5497 int64_t Offset = 0;
5498 for (i = 1; i != e; ++i, ++GTI) {
5499 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5500 // Compute the aggregate offset of constant indices.
5501 if (CI->isZero()) continue;
5502
5503 // Handle a struct index, which adds its field offset to the pointer.
5504 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5505 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5506 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005507 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005508 Offset += Size*CI->getSExtValue();
5509 }
5510 } else {
5511 // Found our variable index.
5512 break;
5513 }
5514 }
5515
5516 // If there are no variable indices, we must have a constant offset, just
5517 // evaluate it the general way.
5518 if (i == e) return 0;
5519
5520 Value *VariableIdx = GEP->getOperand(i);
5521 // Determine the scale factor of the variable element. For example, this is
5522 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005523 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005524
5525 // Verify that there are no other variable indices. If so, emit the hard way.
5526 for (++i, ++GTI; i != e; ++i, ++GTI) {
5527 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5528 if (!CI) return 0;
5529
5530 // Compute the aggregate offset of constant indices.
5531 if (CI->isZero()) continue;
5532
5533 // Handle a struct index, which adds its field offset to the pointer.
5534 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5535 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5536 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005537 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005538 Offset += Size*CI->getSExtValue();
5539 }
5540 }
5541
5542 // Okay, we know we have a single variable index, which must be a
5543 // pointer/array/vector index. If there is no offset, life is simple, return
5544 // the index.
5545 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5546 if (Offset == 0) {
5547 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5548 // we don't need to bother extending: the extension won't affect where the
5549 // computation crosses zero.
5550 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson1d0be152009-08-13 21:58:54 +00005551 VariableIdx = new TruncInst(VariableIdx,
5552 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005553 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005554 return VariableIdx;
5555 }
5556
5557 // Otherwise, there is an index. The computation we will do will be modulo
5558 // the pointer size, so get it.
5559 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5560
5561 Offset &= PtrSizeMask;
5562 VariableScale &= PtrSizeMask;
5563
5564 // To do this transformation, any constant index must be a multiple of the
5565 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5566 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5567 // multiple of the variable scale.
5568 int64_t NewOffs = Offset / (int64_t)VariableScale;
5569 if (Offset != NewOffs*(int64_t)VariableScale)
5570 return 0;
5571
5572 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson1d0be152009-08-13 21:58:54 +00005573 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner10c0d912008-04-22 02:53:33 +00005574 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005575 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005576 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005577 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005578 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005579 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005580}
5581
5582
Reid Spencere4d87aa2006-12-23 06:05:41 +00005583/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005584/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005585Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005586 ICmpInst::Predicate Cond,
5587 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005588 // Look through bitcasts.
5589 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5590 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005591
Chris Lattner574da9b2005-01-13 20:14:25 +00005592 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005593 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005594 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005595 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005596 // know pointers can't overflow since the gep is inbounds. See if we can
5597 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005598 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5599
5600 // If not, synthesize the offset the hard way.
5601 if (Offset == 0)
5602 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005603 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005604 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005605 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005606 // If the base pointers are different, but the indices are the same, just
5607 // compare the base pointer.
5608 if (PtrBase != GEPRHS->getOperand(0)) {
5609 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005610 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005611 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005612 if (IndicesTheSame)
5613 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5614 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5615 IndicesTheSame = false;
5616 break;
5617 }
5618
5619 // If all indices are the same, just compare the base pointers.
5620 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005621 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005622 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005623
5624 // Otherwise, the base pointers are different and the indices are
5625 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005626 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005627 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005628
Chris Lattnere9d782b2005-01-13 22:25:21 +00005629 // If one of the GEPs has all zero indices, recurse.
5630 bool AllZeros = true;
5631 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5632 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5633 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5634 AllZeros = false;
5635 break;
5636 }
5637 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005638 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5639 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005640
5641 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005642 AllZeros = true;
5643 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5644 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5645 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5646 AllZeros = false;
5647 break;
5648 }
5649 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005650 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005651
Chris Lattner4401c9c2005-01-14 00:20:05 +00005652 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5653 // If the GEPs only differ by one index, compare it.
5654 unsigned NumDifferences = 0; // Keep track of # differences.
5655 unsigned DiffOperand = 0; // The operand that differs.
5656 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5657 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005658 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5659 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005660 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005661 NumDifferences = 2;
5662 break;
5663 } else {
5664 if (NumDifferences++) break;
5665 DiffOperand = i;
5666 }
5667 }
5668
5669 if (NumDifferences == 0) // SAME GEP?
5670 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005671 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005672 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005673
Chris Lattner4401c9c2005-01-14 00:20:05 +00005674 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005675 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5676 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005677 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005678 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005679 }
5680 }
5681
Reid Spencere4d87aa2006-12-23 06:05:41 +00005682 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005683 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005684 if (TD &&
5685 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005686 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5687 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5688 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5689 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005690 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005691 }
5692 }
5693 return 0;
5694}
5695
Chris Lattnera5406232008-05-19 20:18:56 +00005696/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5697///
5698Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5699 Instruction *LHSI,
5700 Constant *RHSC) {
5701 if (!isa<ConstantFP>(RHSC)) return 0;
5702 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5703
5704 // Get the width of the mantissa. We don't want to hack on conversions that
5705 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005706 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005707 if (MantissaWidth == -1) return 0; // Unknown.
5708
5709 // Check to see that the input is converted from an integer type that is small
5710 // enough that preserves all bits. TODO: check here for "known" sign bits.
5711 // 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 +00005712 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005713
5714 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005715 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5716 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005717 ++InputSize;
5718
5719 // If the conversion would lose info, don't hack on this.
5720 if ((int)InputSize > MantissaWidth)
5721 return 0;
5722
5723 // Otherwise, we can potentially simplify the comparison. We know that it
5724 // will always come through as an integer value and we know the constant is
5725 // not a NAN (it would have been previously simplified).
5726 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5727
5728 ICmpInst::Predicate Pred;
5729 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005730 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005731 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005732 case FCmpInst::FCMP_OEQ:
5733 Pred = ICmpInst::ICMP_EQ;
5734 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005735 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005736 case FCmpInst::FCMP_OGT:
5737 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5738 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005739 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005740 case FCmpInst::FCMP_OGE:
5741 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5742 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005743 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005744 case FCmpInst::FCMP_OLT:
5745 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5746 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005747 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005748 case FCmpInst::FCMP_OLE:
5749 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5750 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005751 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005752 case FCmpInst::FCMP_ONE:
5753 Pred = ICmpInst::ICMP_NE;
5754 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005755 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005756 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005757 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005758 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005759 }
5760
5761 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5762
5763 // Now we know that the APFloat is a normal number, zero or inf.
5764
Chris Lattner85162782008-05-20 03:50:52 +00005765 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005766 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005767 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005768
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005769 if (!LHSUnsigned) {
5770 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5771 // and large values.
5772 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5773 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5774 APFloat::rmNearestTiesToEven);
5775 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5776 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5777 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005778 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5779 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005780 }
5781 } else {
5782 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5783 // +INF and large values.
5784 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5785 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5786 APFloat::rmNearestTiesToEven);
5787 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5788 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5789 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005790 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5791 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005792 }
Chris Lattnera5406232008-05-19 20:18:56 +00005793 }
5794
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005795 if (!LHSUnsigned) {
5796 // See if the RHS value is < SignedMin.
5797 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5798 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5799 APFloat::rmNearestTiesToEven);
5800 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5801 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5802 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005803 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5804 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005805 }
Chris Lattnera5406232008-05-19 20:18:56 +00005806 }
5807
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005808 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5809 // [0, UMAX], but it may still be fractional. See if it is fractional by
5810 // casting the FP value to the integer value and back, checking for equality.
5811 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005812 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005813 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5814 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005815 if (!RHS.isZero()) {
5816 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005817 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5818 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005819 if (!Equal) {
5820 // If we had a comparison against a fractional value, we have to adjust
5821 // the compare predicate and sometimes the value. RHSC is rounded towards
5822 // zero at this point.
5823 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005824 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005825 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005826 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005827 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005828 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005829 case ICmpInst::ICMP_ULE:
5830 // (float)int <= 4.4 --> int <= 4
5831 // (float)int <= -4.4 --> false
5832 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005833 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005834 break;
5835 case ICmpInst::ICMP_SLE:
5836 // (float)int <= 4.4 --> int <= 4
5837 // (float)int <= -4.4 --> int < -4
5838 if (RHS.isNegative())
5839 Pred = ICmpInst::ICMP_SLT;
5840 break;
5841 case ICmpInst::ICMP_ULT:
5842 // (float)int < -4.4 --> false
5843 // (float)int < 4.4 --> int <= 4
5844 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005845 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005846 Pred = ICmpInst::ICMP_ULE;
5847 break;
5848 case ICmpInst::ICMP_SLT:
5849 // (float)int < -4.4 --> int < -4
5850 // (float)int < 4.4 --> int <= 4
5851 if (!RHS.isNegative())
5852 Pred = ICmpInst::ICMP_SLE;
5853 break;
5854 case ICmpInst::ICMP_UGT:
5855 // (float)int > 4.4 --> int > 4
5856 // (float)int > -4.4 --> true
5857 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005858 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005859 break;
5860 case ICmpInst::ICMP_SGT:
5861 // (float)int > 4.4 --> int > 4
5862 // (float)int > -4.4 --> int >= -4
5863 if (RHS.isNegative())
5864 Pred = ICmpInst::ICMP_SGE;
5865 break;
5866 case ICmpInst::ICMP_UGE:
5867 // (float)int >= -4.4 --> true
5868 // (float)int >= 4.4 --> int > 4
5869 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005870 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005871 Pred = ICmpInst::ICMP_UGT;
5872 break;
5873 case ICmpInst::ICMP_SGE:
5874 // (float)int >= -4.4 --> int >= -4
5875 // (float)int >= 4.4 --> int > 4
5876 if (!RHS.isNegative())
5877 Pred = ICmpInst::ICMP_SGT;
5878 break;
5879 }
Chris Lattnera5406232008-05-19 20:18:56 +00005880 }
5881 }
5882
5883 // Lower this FP comparison into an appropriate integer version of the
5884 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005885 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005886}
5887
Reid Spencere4d87aa2006-12-23 06:05:41 +00005888Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5889 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005890 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005891
Chris Lattner58e97462007-01-14 19:42:17 +00005892 // Fold trivial predicates.
5893 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005894 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005895 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005896 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005897
5898 // Simplify 'fcmp pred X, X'
5899 if (Op0 == Op1) {
5900 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005901 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005902 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5903 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5904 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Anderson5defacc2009-07-31 17:39:07 +00005905 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005906 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5907 case FCmpInst::FCMP_OLT: // True if ordered and less than
5908 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Anderson5defacc2009-07-31 17:39:07 +00005909 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005910
5911 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5912 case FCmpInst::FCMP_ULT: // True if unordered or less than
5913 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5914 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5915 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5916 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005917 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005918 return &I;
5919
5920 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5921 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5922 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5923 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5924 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5925 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005926 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005927 return &I;
5928 }
5929 }
5930
Reid Spencere4d87aa2006-12-23 06:05:41 +00005931 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Anderson1d0be152009-08-13 21:58:54 +00005932 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
Chris Lattnere87597f2004-10-16 18:11:37 +00005933
Reid Spencere4d87aa2006-12-23 06:05:41 +00005934 // Handle fcmp with constant RHS
5935 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005936 // If the constant is a nan, see if we can fold the comparison based on it.
5937 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5938 if (CFP->getValueAPF().isNaN()) {
5939 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005940 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005941 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5942 "Comparison must be either ordered or unordered!");
5943 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005944 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005945 }
5946 }
5947
Reid Spencere4d87aa2006-12-23 06:05:41 +00005948 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5949 switch (LHSI->getOpcode()) {
5950 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005951 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5952 // block. If in the same block, we're encouraging jump threading. If
5953 // not, we are just pessimizing the code by making an i1 phi.
5954 if (LHSI->getParent() == I.getParent())
5955 if (Instruction *NV = FoldOpIntoPhi(I))
5956 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005957 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005958 case Instruction::SIToFP:
5959 case Instruction::UIToFP:
5960 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5961 return NV;
5962 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005963 case Instruction::Select:
5964 // If either operand of the select is a constant, we can fold the
5965 // comparison into the select arms, which will cause one to be
5966 // constant folded and the select turned into a bitwise or.
5967 Value *Op1 = 0, *Op2 = 0;
5968 if (LHSI->hasOneUse()) {
5969 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5970 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005971 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005972 // Insert a new FCmp of the other select operand.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005973 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005974 LHSI->getOperand(2), RHSC,
5975 I.getName()), I);
5976 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5977 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005978 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005979 // Insert a new FCmp of the other select operand.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005980 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005981 LHSI->getOperand(1), RHSC,
5982 I.getName()), I);
5983 }
5984 }
5985
5986 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005987 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005988 break;
5989 }
5990 }
5991
5992 return Changed ? &I : 0;
5993}
5994
5995Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5996 bool Changed = SimplifyCompare(I);
5997 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5998 const Type *Ty = Op0->getType();
5999
6000 // icmp X, X
6001 if (Op0 == Op1)
Owen Anderson1d0be152009-08-13 21:58:54 +00006002 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006003 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00006004
6005 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Anderson1d0be152009-08-13 21:58:54 +00006006 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00006007
Reid Spencere4d87aa2006-12-23 06:05:41 +00006008 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00006009 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00006010 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
6011 isa<ConstantPointerNull>(Op0)) &&
6012 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00006013 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00006014 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006015 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00006016
Reid Spencere4d87aa2006-12-23 06:05:41 +00006017 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00006018 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006019 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006020 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006021 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006022 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00006023 InsertNewInstBefore(Xor, I);
Dan Gohman4ae51262009-08-12 16:23:25 +00006024 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006025 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006026 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006027 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006028
Reid Spencere4d87aa2006-12-23 06:05:41 +00006029 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006030 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006031 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006032 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Dan Gohman4ae51262009-08-12 16:23:25 +00006033 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006034 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006035 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006036 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006037 case ICmpInst::ICMP_SGT:
6038 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006039 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006040 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Dan Gohman4ae51262009-08-12 16:23:25 +00006041 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006042 InsertNewInstBefore(Not, I);
6043 return BinaryOperator::CreateAnd(Not, Op0);
6044 }
6045 case ICmpInst::ICMP_UGE:
6046 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6047 // FALL THROUGH
6048 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Dan Gohman4ae51262009-08-12 16:23:25 +00006049 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006050 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006051 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006052 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006053 case ICmpInst::ICMP_SGE:
6054 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6055 // FALL THROUGH
6056 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Dan Gohman4ae51262009-08-12 16:23:25 +00006057 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006058 InsertNewInstBefore(Not, I);
6059 return BinaryOperator::CreateOr(Not, Op0);
6060 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006061 }
Chris Lattner8b170942002-08-09 23:47:40 +00006062 }
6063
Dan Gohman1c8491e2009-04-25 17:12:48 +00006064 unsigned BitWidth = 0;
6065 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006066 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6067 else if (Ty->isIntOrIntVector())
6068 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006069
6070 bool isSignBit = false;
6071
Dan Gohman81b28ce2008-09-16 18:46:06 +00006072 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006073 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006074 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006075
Chris Lattnerb6566012008-01-05 01:18:20 +00006076 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6077 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006078 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006079 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006080 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006081 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006082
Dan Gohman81b28ce2008-09-16 18:46:06 +00006083 // If we have an icmp le or icmp ge instruction, turn it into the
6084 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6085 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006086 switch (I.getPredicate()) {
6087 default: break;
6088 case ICmpInst::ICMP_ULE:
6089 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006090 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006091 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006092 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006093 case ICmpInst::ICMP_SLE:
6094 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006095 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006096 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006097 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006098 case ICmpInst::ICMP_UGE:
6099 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006100 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006101 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006102 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006103 case ICmpInst::ICMP_SGE:
6104 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006105 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006106 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006107 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006108 }
6109
Chris Lattner183661e2008-07-11 05:40:05 +00006110 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006111 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006112 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006113 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6114 }
6115
6116 // See if we can fold the comparison based on range information we can get
6117 // by checking whether bits are known to be zero or one in the input.
6118 if (BitWidth != 0) {
6119 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6120 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6121
6122 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006123 isSignBit ? APInt::getSignBit(BitWidth)
6124 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006125 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006126 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006127 if (SimplifyDemandedBits(I.getOperandUse(1),
6128 APInt::getAllOnesValue(BitWidth),
6129 Op1KnownZero, Op1KnownOne, 0))
6130 return &I;
6131
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006132 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006133 // in. Compute the Min, Max and RHS values based on the known bits. For the
6134 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006135 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6136 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6137 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6138 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6139 Op0Min, Op0Max);
6140 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6141 Op1Min, Op1Max);
6142 } else {
6143 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6144 Op0Min, Op0Max);
6145 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6146 Op1Min, Op1Max);
6147 }
6148
Chris Lattner183661e2008-07-11 05:40:05 +00006149 // If Min and Max are known to be the same, then SimplifyDemandedBits
6150 // figured out that the LHS is a constant. Just constant fold this now so
6151 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006152 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006153 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006154 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006155 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006156 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006157 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006158
Chris Lattner183661e2008-07-11 05:40:05 +00006159 // Based on the range information we know about the LHS, see if we can
6160 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006161 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006162 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006163 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006164 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006165 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006166 break;
6167 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006168 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006169 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006170 break;
6171 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006172 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006173 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006174 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006175 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006176 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006177 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006178 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6179 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006180 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006181 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006182
6183 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6184 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006185 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006186 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006187 }
Chris Lattner84dff672008-07-11 05:08:55 +00006188 break;
6189 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006190 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006191 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006192 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006193 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006194
6195 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006196 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006197 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6198 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006199 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006200 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006201
6202 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6203 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006204 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006205 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006206 }
Chris Lattner84dff672008-07-11 05:08:55 +00006207 break;
6208 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006209 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006210 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006211 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006212 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006213 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006214 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006215 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6216 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006217 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006218 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006219 }
Chris Lattner84dff672008-07-11 05:08:55 +00006220 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006221 case ICmpInst::ICMP_SGT:
6222 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006223 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006224 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006225 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006226
6227 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006228 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006229 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6230 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006231 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006232 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006233 }
6234 break;
6235 case ICmpInst::ICMP_SGE:
6236 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6237 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006238 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006239 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006240 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006241 break;
6242 case ICmpInst::ICMP_SLE:
6243 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6244 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006245 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006246 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006247 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006248 break;
6249 case ICmpInst::ICMP_UGE:
6250 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6251 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006252 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006253 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006254 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006255 break;
6256 case ICmpInst::ICMP_ULE:
6257 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6258 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006259 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006260 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006261 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006262 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006263 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006264
6265 // Turn a signed comparison into an unsigned one if both operands
6266 // are known to have the same sign.
6267 if (I.isSignedPredicate() &&
6268 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6269 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006270 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006271 }
6272
6273 // Test if the ICmpInst instruction is used exclusively by a select as
6274 // part of a minimum or maximum operation. If so, refrain from doing
6275 // any other folding. This helps out other analyses which understand
6276 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6277 // and CodeGen. And in this case, at least one of the comparison
6278 // operands has at least one user besides the compare (the select),
6279 // which would often largely negate the benefit of folding anyway.
6280 if (I.hasOneUse())
6281 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6282 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6283 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6284 return 0;
6285
6286 // See if we are doing a comparison between a constant and an instruction that
6287 // can be folded into the comparison.
6288 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006289 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006290 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006291 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006292 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006293 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6294 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006295 }
6296
Chris Lattner01deb9d2007-04-03 17:43:25 +00006297 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006298 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6299 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6300 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006301 case Instruction::GetElementPtr:
6302 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006303 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006304 bool isAllZeros = true;
6305 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6306 if (!isa<Constant>(LHSI->getOperand(i)) ||
6307 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6308 isAllZeros = false;
6309 break;
6310 }
6311 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006312 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006313 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006314 }
6315 break;
6316
Chris Lattner6970b662005-04-23 15:31:55 +00006317 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006318 // Only fold icmp into the PHI if the phi and fcmp are in the same
6319 // block. If in the same block, we're encouraging jump threading. If
6320 // not, we are just pessimizing the code by making an i1 phi.
6321 if (LHSI->getParent() == I.getParent())
6322 if (Instruction *NV = FoldOpIntoPhi(I))
6323 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006324 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006325 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006326 // If either operand of the select is a constant, we can fold the
6327 // comparison into the select arms, which will cause one to be
6328 // constant folded and the select turned into a bitwise or.
6329 Value *Op1 = 0, *Op2 = 0;
6330 if (LHSI->hasOneUse()) {
6331 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6332 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006333 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006334 // Insert a new ICmp of the other select operand.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006335 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006336 LHSI->getOperand(2), RHSC,
6337 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006338 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6339 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006340 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006341 // Insert a new ICmp of the other select operand.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006342 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006343 LHSI->getOperand(1), RHSC,
6344 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006345 }
6346 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006347
Chris Lattner6970b662005-04-23 15:31:55 +00006348 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006349 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006350 break;
6351 }
Chris Lattner4802d902007-04-06 18:57:34 +00006352 case Instruction::Malloc:
6353 // If we have (malloc != null), and if the malloc has a single use, we
6354 // can assume it is successful and remove the malloc.
6355 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00006356 Worklist.Add(LHSI);
Owen Anderson1d0be152009-08-13 21:58:54 +00006357 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006358 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006359 }
6360 break;
6361 }
Chris Lattner6970b662005-04-23 15:31:55 +00006362 }
6363
Reid Spencere4d87aa2006-12-23 06:05:41 +00006364 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006365 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006366 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006367 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006368 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006369 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6370 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006371 return NI;
6372
Reid Spencere4d87aa2006-12-23 06:05:41 +00006373 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006374 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6375 // now.
6376 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6377 if (isa<PointerType>(Op0->getType()) &&
6378 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006379 // We keep moving the cast from the left operand over to the right
6380 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006381 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006382
Chris Lattner57d86372007-01-06 01:45:59 +00006383 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6384 // so eliminate it as well.
6385 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6386 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006387
Chris Lattnerde90b762003-11-03 04:25:02 +00006388 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006389 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006390 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006391 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006392 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006393 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006394 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006395 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006396 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006397 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006398 }
Chris Lattner57d86372007-01-06 01:45:59 +00006399 }
6400
6401 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006402 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006403 // This comes up when you have code like
6404 // int X = A < B;
6405 // if (X) ...
6406 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006407 // with a constant or another cast from the same type.
6408 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006409 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006410 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006411 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006412
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006413 // See if it's the same type of instruction on the left and right.
6414 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6415 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006416 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006417 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006418 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006419 default: break;
6420 case Instruction::Add:
6421 case Instruction::Sub:
6422 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006423 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006424 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006425 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006426 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6427 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6428 if (CI->getValue().isSignBit()) {
6429 ICmpInst::Predicate Pred = I.isSignedPredicate()
6430 ? I.getUnsignedPredicate()
6431 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006432 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006433 Op1I->getOperand(0));
6434 }
6435
6436 if (CI->getValue().isMaxSignedValue()) {
6437 ICmpInst::Predicate Pred = I.isSignedPredicate()
6438 ? I.getUnsignedPredicate()
6439 : I.getSignedPredicate();
6440 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006441 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006442 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006443 }
6444 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006445 break;
6446 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006447 if (!I.isEquality())
6448 break;
6449
Nick Lewycky5d52c452008-08-21 05:56:10 +00006450 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6451 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6452 // Mask = -1 >> count-trailing-zeros(Cst).
6453 if (!CI->isZero() && !CI->isOne()) {
6454 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006455 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006456 APInt::getLowBitsSet(AP.getBitWidth(),
6457 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006458 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006459 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6460 Mask);
6461 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6462 Mask);
6463 InsertNewInstBefore(And1, I);
6464 InsertNewInstBefore(And2, I);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006465 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006466 }
6467 }
6468 break;
6469 }
6470 }
6471 }
6472 }
6473
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006474 // ~x < ~y --> y < x
6475 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006476 if (match(Op0, m_Not(m_Value(A))) &&
6477 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006478 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006479 }
6480
Chris Lattner65b72ba2006-09-18 04:22:48 +00006481 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006482 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006483
6484 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006485 if (match(Op0, m_Neg(m_Value(A))) &&
6486 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006487 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006488
Dan Gohman4ae51262009-08-12 16:23:25 +00006489 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006490 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6491 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006492 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006493 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006494 }
6495
Dan Gohman4ae51262009-08-12 16:23:25 +00006496 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006497 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006498 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006499 if (match(B, m_ConstantInt(C1)) &&
6500 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006501 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006502 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattnercb504b92008-11-16 05:38:51 +00006503 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006504 return new ICmpInst(I.getPredicate(), A,
Chris Lattnercb504b92008-11-16 05:38:51 +00006505 InsertNewInstBefore(Xor, I));
6506 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006507
6508 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006509 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6510 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6511 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6512 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006513 }
6514 }
6515
Dan Gohman4ae51262009-08-12 16:23:25 +00006516 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006517 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006518 // A == (A^B) -> B == 0
6519 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006520 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006521 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006522 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006523
6524 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006525 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006526 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006527 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006528
6529 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006530 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006531 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006532 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006533
Chris Lattner9c2328e2006-11-14 06:06:06 +00006534 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6535 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006536 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6537 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006538 Value *X = 0, *Y = 0, *Z = 0;
6539
6540 if (A == C) {
6541 X = B; Y = D; Z = A;
6542 } else if (A == D) {
6543 X = B; Y = C; Z = A;
6544 } else if (B == C) {
6545 X = A; Y = D; Z = B;
6546 } else if (B == D) {
6547 X = A; Y = C; Z = B;
6548 }
6549
6550 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006551 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6552 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006553 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006554 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006555 return &I;
6556 }
6557 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006558 }
Chris Lattner7e708292002-06-25 16:13:24 +00006559 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006560}
6561
Chris Lattner562ef782007-06-20 23:46:26 +00006562
6563/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6564/// and CmpRHS are both known to be integer constants.
6565Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6566 ConstantInt *DivRHS) {
6567 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6568 const APInt &CmpRHSV = CmpRHS->getValue();
6569
6570 // FIXME: If the operand types don't match the type of the divide
6571 // then don't attempt this transform. The code below doesn't have the
6572 // logic to deal with a signed divide and an unsigned compare (and
6573 // vice versa). This is because (x /s C1) <s C2 produces different
6574 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6575 // (x /u C1) <u C2. Simply casting the operands and result won't
6576 // work. :( The if statement below tests that condition and bails
6577 // if it finds it.
6578 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6579 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6580 return 0;
6581 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006582 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006583 if (DivIsSigned && DivRHS->isAllOnesValue())
6584 return 0; // The overflow computation also screws up here
6585 if (DivRHS->isOne())
6586 return 0; // Not worth bothering, and eliminates some funny cases
6587 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006588
6589 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6590 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6591 // C2 (CI). By solving for X we can turn this into a range check
6592 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006593 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006594
6595 // Determine if the product overflows by seeing if the product is
6596 // not equal to the divide. Make sure we do the same kind of divide
6597 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006598 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6599 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006600
6601 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006602 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006603
Chris Lattner1dbfd482007-06-21 18:11:19 +00006604 // Figure out the interval that is being checked. For example, a comparison
6605 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6606 // Compute this interval based on the constants involved and the signedness of
6607 // the compare/divide. This computes a half-open interval, keeping track of
6608 // whether either value in the interval overflows. After analysis each
6609 // overflow variable is set to 0 if it's corresponding bound variable is valid
6610 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6611 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006612 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006613
Chris Lattner562ef782007-06-20 23:46:26 +00006614 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006615 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006616 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006617 HiOverflow = LoOverflow = ProdOV;
6618 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006619 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006620 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006621 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006622 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006623 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006624 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006625 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006626 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6627 HiOverflow = LoOverflow = ProdOV;
6628 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006629 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006630 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006631 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006632 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006633 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6634 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006635 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006636 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006637 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006638 true) ? -1 : 0;
6639 }
Chris Lattner562ef782007-06-20 23:46:26 +00006640 }
Dan Gohman76491272008-02-13 22:09:18 +00006641 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006642 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006643 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006644 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006645 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006646 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6647 HiOverflow = 1; // [INTMIN+1, overflow)
6648 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6649 }
Dan Gohman76491272008-02-13 22:09:18 +00006650 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006651 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006652 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006653 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006654 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006655 LoOverflow = AddWithOverflow(LoBound, HiBound,
6656 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006657 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006658 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6659 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006660 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006661 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006662 }
6663
Chris Lattner1dbfd482007-06-21 18:11:19 +00006664 // Dividing by a negative swaps the condition. LT <-> GT
6665 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006666 }
6667
6668 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006669 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006670 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006671 case ICmpInst::ICMP_EQ:
6672 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006673 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006674 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006675 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006676 ICmpInst::ICMP_UGE, X, LoBound);
6677 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006678 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006679 ICmpInst::ICMP_ULT, X, HiBound);
6680 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006681 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006682 case ICmpInst::ICMP_NE:
6683 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006684 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006685 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006686 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006687 ICmpInst::ICMP_ULT, X, LoBound);
6688 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006689 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006690 ICmpInst::ICMP_UGE, X, HiBound);
6691 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006692 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006693 case ICmpInst::ICMP_ULT:
6694 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006695 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006696 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006697 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006698 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006699 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006700 case ICmpInst::ICMP_UGT:
6701 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006702 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006703 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006704 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006705 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006706 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006707 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006708 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006709 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006710 }
6711}
6712
6713
Chris Lattner01deb9d2007-04-03 17:43:25 +00006714/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6715///
6716Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6717 Instruction *LHSI,
6718 ConstantInt *RHS) {
6719 const APInt &RHSV = RHS->getValue();
6720
6721 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006722 case Instruction::Trunc:
6723 if (ICI.isEquality() && LHSI->hasOneUse()) {
6724 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6725 // of the high bits truncated out of x are known.
6726 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6727 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6728 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6729 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6730 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6731
6732 // If all the high bits are known, we can do this xform.
6733 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6734 // Pull in the high bits from known-ones set.
6735 APInt NewRHS(RHS->getValue());
6736 NewRHS.zext(SrcBits);
6737 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006738 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006739 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006740 }
6741 }
6742 break;
6743
Duncan Sands0091bf22007-04-04 06:42:45 +00006744 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006745 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6746 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6747 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006748 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6749 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006750 Value *CompareVal = LHSI->getOperand(0);
6751
6752 // If the sign bit of the XorCST is not set, there is no change to
6753 // the operation, just stop using the Xor.
6754 if (!XorCST->getValue().isNegative()) {
6755 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006756 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006757 return &ICI;
6758 }
6759
6760 // Was the old condition true if the operand is positive?
6761 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6762
6763 // If so, the new one isn't.
6764 isTrueIfPositive ^= true;
6765
6766 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006767 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006768 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006769 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006770 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006771 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006772 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006773
6774 if (LHSI->hasOneUse()) {
6775 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6776 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6777 const APInt &SignBit = XorCST->getValue();
6778 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6779 ? ICI.getUnsignedPredicate()
6780 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006781 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006782 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006783 }
6784
6785 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006786 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006787 const APInt &NotSignBit = XorCST->getValue();
6788 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6789 ? ICI.getUnsignedPredicate()
6790 : ICI.getSignedPredicate();
6791 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006792 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006793 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006794 }
6795 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006796 }
6797 break;
6798 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6799 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6800 LHSI->getOperand(0)->hasOneUse()) {
6801 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6802
6803 // If the LHS is an AND of a truncating cast, we can widen the
6804 // and/compare to be the input width without changing the value
6805 // produced, eliminating a cast.
6806 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6807 // We can do this transformation if either the AND constant does not
6808 // have its sign bit set or if it is an equality comparison.
6809 // Extending a relational comparison when we're checking the sign
6810 // bit would not work.
6811 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006812 (ICI.isEquality() ||
6813 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006814 uint32_t BitWidth =
6815 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6816 APInt NewCST = AndCST->getValue();
6817 NewCST.zext(BitWidth);
6818 APInt NewCI = RHSV;
6819 NewCI.zext(BitWidth);
6820 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006821 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006822 ConstantInt::get(*Context, NewCST), LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006823 InsertNewInstBefore(NewAnd, ICI);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006824 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006825 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006826 }
6827 }
6828
6829 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6830 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6831 // happens a LOT in code produced by the C front-end, for bitfield
6832 // access.
6833 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6834 if (Shift && !Shift->isShift())
6835 Shift = 0;
6836
6837 ConstantInt *ShAmt;
6838 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6839 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6840 const Type *AndTy = AndCST->getType(); // Type of the and.
6841
6842 // We can fold this as long as we can't shift unknown bits
6843 // into the mask. This can only happen with signed shift
6844 // rights, as they sign-extend.
6845 if (ShAmt) {
6846 bool CanFold = Shift->isLogicalShift();
6847 if (!CanFold) {
6848 // To test for the bad case of the signed shr, see if any
6849 // of the bits shifted in could be tested after the mask.
6850 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6851 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6852
6853 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6854 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6855 AndCST->getValue()) == 0)
6856 CanFold = true;
6857 }
6858
6859 if (CanFold) {
6860 Constant *NewCst;
6861 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006862 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006863 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006864 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006865
6866 // Check to see if we are shifting out any of the bits being
6867 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006868 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006869 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006870 // If we shifted bits out, the fold is not going to work out.
6871 // As a special case, check to see if this means that the
6872 // result is always true or false now.
6873 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006874 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006875 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006876 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006877 } else {
6878 ICI.setOperand(1, NewCst);
6879 Constant *NewAndCST;
6880 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006881 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006882 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006883 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006884 LHSI->setOperand(1, NewAndCST);
6885 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006886 Worklist.Add(Shift); // Shift is dead.
Chris Lattnerc3a3e362009-08-30 06:20:05 +00006887 AddOperandsToWorkList(ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006888 return &ICI;
6889 }
6890 }
6891 }
6892
6893 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6894 // preferable because it allows the C<<Y expression to be hoisted out
6895 // of a loop if Y is invariant and X is not.
6896 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006897 ICI.isEquality() && !Shift->isArithmeticShift() &&
6898 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006899 // Compute C << Y.
6900 Value *NS;
6901 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006902 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006903 Shift->getOperand(1), "tmp");
6904 } else {
6905 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006906 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006907 Shift->getOperand(1), "tmp");
6908 }
6909 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6910
6911 // Compute X & (C << Y).
6912 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006913 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006914 InsertNewInstBefore(NewAnd, ICI);
6915
6916 ICI.setOperand(0, NewAnd);
6917 return &ICI;
6918 }
6919 }
6920 break;
6921
Chris Lattnera0141b92007-07-15 20:42:37 +00006922 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6923 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6924 if (!ShAmt) break;
6925
6926 uint32_t TypeBits = RHSV.getBitWidth();
6927
6928 // Check that the shift amount is in range. If not, don't perform
6929 // undefined shifts. When the shift is visited it will be
6930 // simplified.
6931 if (ShAmt->uge(TypeBits))
6932 break;
6933
6934 if (ICI.isEquality()) {
6935 // If we are comparing against bits always shifted out, the
6936 // comparison cannot succeed.
6937 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006938 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006939 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006940 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6941 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006942 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006943 return ReplaceInstUsesWith(ICI, Cst);
6944 }
6945
6946 if (LHSI->hasOneUse()) {
6947 // Otherwise strength reduce the shift into an and.
6948 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6949 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006950 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006951 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006952
Chris Lattnera0141b92007-07-15 20:42:37 +00006953 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006954 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006955 Mask, LHSI->getName()+".mask");
6956 Value *And = InsertNewInstBefore(AndI, ICI);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006957 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006958 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006959 }
6960 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006961
6962 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6963 bool TrueIfSigned = false;
6964 if (LHSI->hasOneUse() &&
6965 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6966 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006967 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006968 (TypeBits-ShAmt->getZExtValue()-1));
6969 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006970 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006971 Mask, LHSI->getName()+".mask");
6972 Value *And = InsertNewInstBefore(AndI, ICI);
6973
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006974 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006975 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006976 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006977 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006978 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006979
6980 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006981 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006982 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006983 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006984 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006985
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006986 // Check that the shift amount is in range. If not, don't perform
6987 // undefined shifts. When the shift is visited it will be
6988 // simplified.
6989 uint32_t TypeBits = RHSV.getBitWidth();
6990 if (ShAmt->uge(TypeBits))
6991 break;
6992
6993 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006994
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006995 // If we are comparing against bits always shifted out, the
6996 // comparison cannot succeed.
6997 APInt Comp = RHSV << ShAmtVal;
6998 if (LHSI->getOpcode() == Instruction::LShr)
6999 Comp = Comp.lshr(ShAmtVal);
7000 else
7001 Comp = Comp.ashr(ShAmtVal);
7002
7003 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7004 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007005 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007006 return ReplaceInstUsesWith(ICI, Cst);
7007 }
7008
7009 // Otherwise, check to see if the bits shifted out are known to be zero.
7010 // If so, we can compare against the unshifted value:
7011 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007012 if (LHSI->hasOneUse() &&
7013 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007014 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007015 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007016 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007017 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007018
Evan Chengf30752c2008-04-23 00:38:06 +00007019 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007020 // Otherwise strength reduce the shift into an and.
7021 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007022 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007023
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007024 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007025 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007026 Mask, LHSI->getName()+".mask");
7027 Value *And = InsertNewInstBefore(AndI, ICI);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007028 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007029 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007030 }
7031 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007032 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007033
7034 case Instruction::SDiv:
7035 case Instruction::UDiv:
7036 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7037 // Fold this div into the comparison, producing a range check.
7038 // Determine, based on the divide type, what the range is being
7039 // checked. If there is an overflow on the low or high side, remember
7040 // it, otherwise compute the range [low, hi) bounding the new value.
7041 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007042 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7043 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7044 DivRHS))
7045 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007046 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007047
7048 case Instruction::Add:
7049 // Fold: icmp pred (add, X, C1), C2
7050
7051 if (!ICI.isEquality()) {
7052 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7053 if (!LHSC) break;
7054 const APInt &LHSV = LHSC->getValue();
7055
7056 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7057 .subtract(LHSV);
7058
7059 if (ICI.isSignedPredicate()) {
7060 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007061 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007062 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007063 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007064 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007065 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007066 }
7067 } else {
7068 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007069 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007070 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007071 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007072 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007073 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007074 }
7075 }
7076 }
7077 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007078 }
7079
7080 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7081 if (ICI.isEquality()) {
7082 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7083
7084 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7085 // the second operand is a constant, simplify a bit.
7086 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7087 switch (BO->getOpcode()) {
7088 case Instruction::SRem:
7089 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7090 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7091 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7092 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7093 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007094 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007095 BO->getName());
7096 InsertNewInstBefore(NewRem, ICI);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007097 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007098 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007099 }
7100 }
7101 break;
7102 case Instruction::Add:
7103 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7104 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7105 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007106 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007107 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007108 } else if (RHSV == 0) {
7109 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7110 // efficiently invertible, or if the add has just this one use.
7111 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7112
Dan Gohman186a6362009-08-12 16:04:34 +00007113 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007114 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007115 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007116 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007117 else if (BO->hasOneUse()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00007118 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007119 InsertNewInstBefore(Neg, ICI);
7120 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007121 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007122 }
7123 }
7124 break;
7125 case Instruction::Xor:
7126 // For the xor case, we can xor two constants together, eliminating
7127 // the explicit xor.
7128 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007129 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007130 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007131
7132 // FALLTHROUGH
7133 case Instruction::Sub:
7134 // Replace (([sub|xor] A, B) != 0) with (A != B)
7135 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007136 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007137 BO->getOperand(1));
7138 break;
7139
7140 case Instruction::Or:
7141 // If bits are being or'd in that are not present in the constant we
7142 // are comparing against, then the comparison could never succeed!
7143 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007144 Constant *NotCI = ConstantExpr::getNot(RHS);
7145 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007146 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007147 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007148 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007149 }
7150 break;
7151
7152 case Instruction::And:
7153 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7154 // If bits are being compared against that are and'd out, then the
7155 // comparison can never succeed!
7156 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007157 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007158 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007159 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007160
7161 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7162 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007163 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007164 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007165 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007166
7167 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007168 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007169 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007170 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007171 ICmpInst::Predicate pred = isICMP_NE ?
7172 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007173 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007174 }
7175
7176 // ((X & ~7) == 0) --> X < 8
7177 if (RHSV == 0 && isHighOnes(BOC)) {
7178 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007179 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007180 ICmpInst::Predicate pred = isICMP_NE ?
7181 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007182 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007183 }
7184 }
7185 default: break;
7186 }
7187 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7188 // Handle icmp {eq|ne} <intrinsic>, intcst.
7189 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007190 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007191 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007192 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007193 return &ICI;
7194 }
7195 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007196 }
7197 return 0;
7198}
7199
7200/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7201/// We only handle extending casts so far.
7202///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007203Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7204 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007205 Value *LHSCIOp = LHSCI->getOperand(0);
7206 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007207 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007208 Value *RHSCIOp;
7209
Chris Lattner8c756c12007-05-05 22:41:33 +00007210 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7211 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007212 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7213 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007214 cast<IntegerType>(DestTy)->getBitWidth()) {
7215 Value *RHSOp = 0;
7216 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007217 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007218 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7219 RHSOp = RHSC->getOperand(0);
7220 // If the pointer types don't match, insert a bitcast.
7221 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007222 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007223 }
7224
7225 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007226 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007227 }
7228
7229 // The code below only handles extension cast instructions, so far.
7230 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007231 if (LHSCI->getOpcode() != Instruction::ZExt &&
7232 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007233 return 0;
7234
Reid Spencere4d87aa2006-12-23 06:05:41 +00007235 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7236 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007237
Reid Spencere4d87aa2006-12-23 06:05:41 +00007238 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007239 // Not an extension from the same type?
7240 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007241 if (RHSCIOp->getType() != LHSCIOp->getType())
7242 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007243
Nick Lewycky4189a532008-01-28 03:48:02 +00007244 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007245 // and the other is a zext), then we can't handle this.
7246 if (CI->getOpcode() != LHSCI->getOpcode())
7247 return 0;
7248
Nick Lewycky4189a532008-01-28 03:48:02 +00007249 // Deal with equality cases early.
7250 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007251 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007252
7253 // A signed comparison of sign extended values simplifies into a
7254 // signed comparison.
7255 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007256 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007257
7258 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007259 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007260 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007261
Reid Spencere4d87aa2006-12-23 06:05:41 +00007262 // If we aren't dealing with a constant on the RHS, exit early
7263 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7264 if (!CI)
7265 return 0;
7266
7267 // Compute the constant that would happen if we truncated to SrcTy then
7268 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007269 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7270 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007271 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007272
7273 // If the re-extended constant didn't change...
7274 if (Res2 == CI) {
7275 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7276 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007277 // %A = sext i16 %X to i32
7278 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007279 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007280 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007281 // because %A may have negative value.
7282 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007283 // However, we allow this when the compare is EQ/NE, because they are
7284 // signless.
7285 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007286 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007287 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007288 }
7289
7290 // The re-extended constant changed so the constant cannot be represented
7291 // in the shorter type. Consequently, we cannot emit a simple comparison.
7292
7293 // First, handle some easy cases. We know the result cannot be equal at this
7294 // point so handle the ICI.isEquality() cases
7295 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007296 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007297 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007298 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007299
7300 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7301 // should have been folded away previously and not enter in here.
7302 Value *Result;
7303 if (isSignedCmp) {
7304 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007305 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007306 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007307 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007308 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007309 } else {
7310 // We're performing an unsigned comparison.
7311 if (isSignedExt) {
7312 // We're performing an unsigned comp with a sign extended value.
7313 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007314 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007315 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT,
Owen Anderson333c4002009-07-09 23:48:35 +00007316 LHSCIOp, NegOne, ICI.getName()), ICI);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007317 } else {
7318 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007319 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007320 }
7321 }
7322
7323 // Finally, return the value computed.
7324 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007325 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007326 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007327
7328 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7329 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7330 "ICmp should be folded!");
7331 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007332 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007333 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007334}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007335
Reid Spencer832254e2007-02-02 02:16:23 +00007336Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7337 return commonShiftTransforms(I);
7338}
7339
7340Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7341 return commonShiftTransforms(I);
7342}
7343
7344Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007345 if (Instruction *R = commonShiftTransforms(I))
7346 return R;
7347
7348 Value *Op0 = I.getOperand(0);
7349
7350 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7351 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7352 if (CSI->isAllOnesValue())
7353 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007354
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007355 // See if we can turn a signed shr into an unsigned shr.
7356 if (MaskedValueIsZero(Op0,
7357 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7358 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7359
7360 // Arithmetic shifting an all-sign-bit value is a no-op.
7361 unsigned NumSignBits = ComputeNumSignBits(Op0);
7362 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7363 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007364
Chris Lattner348f6652007-12-06 01:59:46 +00007365 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007366}
7367
7368Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7369 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007370 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007371
7372 // shl X, 0 == X and shr X, 0 == X
7373 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007374 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7375 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007376 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007377
Reid Spencere4d87aa2006-12-23 06:05:41 +00007378 if (isa<UndefValue>(Op0)) {
7379 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007380 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007381 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007382 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007383 }
7384 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007385 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7386 return ReplaceInstUsesWith(I, Op0);
7387 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007388 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007389 }
7390
Dan Gohman9004c8a2009-05-21 02:28:33 +00007391 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007392 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007393 return &I;
7394
Chris Lattner2eefe512004-04-09 19:05:30 +00007395 // Try to fold constant and into select arguments.
7396 if (isa<Constant>(Op0))
7397 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007398 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007399 return R;
7400
Reid Spencerb83eb642006-10-20 07:07:24 +00007401 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007402 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7403 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007404 return 0;
7405}
7406
Reid Spencerb83eb642006-10-20 07:07:24 +00007407Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007408 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007409 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007410
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007411 // See if we can simplify any instructions used by the instruction whose sole
7412 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007413 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007414
Dan Gohmana119de82009-06-14 23:30:43 +00007415 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7416 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007417 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007418 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007419 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007420 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007421 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007422 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007423 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007424 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007425 }
7426
7427 // ((X*C1) << C2) == (X * (C1 << C2))
7428 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7429 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7430 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007431 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007432 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007433
7434 // Try to fold constant and into select arguments.
7435 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7436 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7437 return R;
7438 if (isa<PHINode>(Op0))
7439 if (Instruction *NV = FoldOpIntoPhi(I))
7440 return NV;
7441
Chris Lattner8999dd32007-12-22 09:07:47 +00007442 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7443 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7444 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7445 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7446 // place. Don't try to do this transformation in this case. Also, we
7447 // require that the input operand is a shift-by-constant so that we have
7448 // confidence that the shifts will get folded together. We could do this
7449 // xform in more cases, but it is unlikely to be profitable.
7450 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7451 isa<ConstantInt>(TrOp->getOperand(1))) {
7452 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007453 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007454 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007455 I.getName());
7456 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7457
7458 // For logical shifts, the truncation has the effect of making the high
7459 // part of the register be zeros. Emulate this by inserting an AND to
7460 // clear the top bits as needed. This 'and' will usually be zapped by
7461 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007462 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7463 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007464 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7465
7466 // The mask we constructed says what the trunc would do if occurring
7467 // between the shifts. We want to know the effect *after* the second
7468 // shift. We know that it is a logical shift by a constant, so adjust the
7469 // mask as appropriate.
7470 if (I.getOpcode() == Instruction::Shl)
7471 MaskV <<= Op1->getZExtValue();
7472 else {
7473 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7474 MaskV = MaskV.lshr(Op1->getZExtValue());
7475 }
7476
Owen Andersond672ecb2009-07-03 00:17:18 +00007477 Instruction *And =
Owen Andersoneed707b2009-07-24 23:12:02 +00007478 BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
Owen Andersond672ecb2009-07-03 00:17:18 +00007479 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007480 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7481
7482 // Return the value truncated to the interesting size.
7483 return new TruncInst(And, I.getType());
7484 }
7485 }
7486
Chris Lattner4d5542c2006-01-06 07:12:35 +00007487 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007488 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7489 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7490 Value *V1, *V2;
7491 ConstantInt *CC;
7492 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007493 default: break;
7494 case Instruction::Add:
7495 case Instruction::And:
7496 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007497 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007498 // These operators commute.
7499 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007500 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007501 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007502 m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007503 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007504 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007505 Op0BO->getName());
7506 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007507 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007508 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007509 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007510 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007511 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007512 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007513 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007514 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007515
Chris Lattner150f12a2005-09-18 06:30:59 +00007516 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007517 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007518 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007519 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007520 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007521 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007522 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007523 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007524 Op0BO->getOperand(0), Op1,
7525 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007526 InsertNewInstBefore(YS, I); // (Y << C)
7527 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007528 BinaryOperator::CreateAnd(V1,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007529 ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007530 V1->getName()+".mask");
7531 InsertNewInstBefore(XM, I); // X & (CC << C)
7532
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007533 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007534 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007535 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007536
Reid Spencera07cb7d2007-02-02 14:41:37 +00007537 // FALL THROUGH.
7538 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007539 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007540 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007541 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007542 m_Specific(Op1)))) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007543 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007544 Op0BO->getOperand(1), Op1,
7545 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007546 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007547 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007548 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007549 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007550 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007551 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007552 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007553 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007554 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007555
Chris Lattner13d4ab42006-05-31 21:14:00 +00007556 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007557 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7558 match(Op0BO->getOperand(0),
7559 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007560 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007561 cast<BinaryOperator>(Op0BO->getOperand(0))
7562 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007563 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007564 Op0BO->getOperand(1), Op1,
7565 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007566 InsertNewInstBefore(YS, I); // (Y << C)
7567 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007568 BinaryOperator::CreateAnd(V1,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007569 ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007570 V1->getName()+".mask");
7571 InsertNewInstBefore(XM, I); // X & (CC << C)
7572
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007573 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007574 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007575
Chris Lattner11021cb2005-09-18 05:12:10 +00007576 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007577 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007578 }
7579
7580
7581 // If the operand is an bitwise operator with a constant RHS, and the
7582 // shift is the only use, we can pull it out of the shift.
7583 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7584 bool isValid = true; // Valid only for And, Or, Xor
7585 bool highBitSet = false; // Transform if high bit of constant set?
7586
7587 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007588 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007589 case Instruction::Add:
7590 isValid = isLeftShift;
7591 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007592 case Instruction::Or:
7593 case Instruction::Xor:
7594 highBitSet = false;
7595 break;
7596 case Instruction::And:
7597 highBitSet = true;
7598 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007599 }
7600
7601 // If this is a signed shift right, and the high bit is modified
7602 // by the logical operation, do not perform the transformation.
7603 // The highBitSet boolean indicates the value of the high bit of
7604 // the constant which would cause it to be modified for this
7605 // operation.
7606 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007607 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007608 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007609
7610 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007611 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007612
7613 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007614 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007615 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007616 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007617
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007618 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007619 NewRHS);
7620 }
7621 }
7622 }
7623 }
7624
Chris Lattnerad0124c2006-01-06 07:52:12 +00007625 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007626 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7627 if (ShiftOp && !ShiftOp->isShift())
7628 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007629
Reid Spencerb83eb642006-10-20 07:07:24 +00007630 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007631 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007632 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7633 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007634 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7635 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7636 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007637
Zhou Sheng4351c642007-04-02 08:20:41 +00007638 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007639
7640 const IntegerType *Ty = cast<IntegerType>(I.getType());
7641
7642 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007643 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007644 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7645 // saturates.
7646 if (AmtSum >= TypeBits) {
7647 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007648 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007649 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7650 }
7651
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007652 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007653 ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007654 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7655 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007656 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007657 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007658
Chris Lattnerb87056f2007-02-05 00:57:54 +00007659 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007660 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007661 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7662 I.getOpcode() == Instruction::LShr) {
7663 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007664 if (AmtSum >= TypeBits)
7665 AmtSum = TypeBits-1;
7666
Chris Lattnerb87056f2007-02-05 00:57:54 +00007667 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007668 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007669 InsertNewInstBefore(Shift, I);
7670
Zhou Shenge9e03f62007-03-28 15:02:20 +00007671 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007672 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007673 }
7674
Chris Lattnerb87056f2007-02-05 00:57:54 +00007675 // Okay, if we get here, one shift must be left, and the other shift must be
7676 // right. See if the amounts are equal.
7677 if (ShiftAmt1 == ShiftAmt2) {
7678 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7679 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007680 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007681 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007682 }
7683 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7684 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007685 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007686 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007687 }
7688 // We can simplify ((X << C) >>s C) into a trunc + sext.
7689 // NOTE: we could do this for any C, but that would make 'unusual' integer
7690 // types. For now, just stick to ones well-supported by the code
7691 // generators.
7692 const Type *SExtType = 0;
7693 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007694 case 1 :
7695 case 8 :
7696 case 16 :
7697 case 32 :
7698 case 64 :
7699 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007700 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007701 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007702 default: break;
7703 }
7704 if (SExtType) {
7705 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7706 InsertNewInstBefore(NewTrunc, I);
7707 return new SExtInst(NewTrunc, Ty);
7708 }
7709 // Otherwise, we can't handle it yet.
7710 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007711 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007712
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007713 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007714 if (I.getOpcode() == Instruction::Shl) {
7715 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7716 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007717 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007718 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007719 InsertNewInstBefore(Shift, I);
7720
Reid Spencer55702aa2007-03-25 21:11:44 +00007721 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007722 return BinaryOperator::CreateAnd(Shift,
7723 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007724 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007725
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007726 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007727 if (I.getOpcode() == Instruction::LShr) {
7728 assert(ShiftOp->getOpcode() == Instruction::Shl);
7729 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007730 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007731 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007732
Reid Spencerd5e30f02007-03-26 17:18:58 +00007733 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007734 return BinaryOperator::CreateAnd(Shift,
7735 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007736 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007737
7738 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7739 } else {
7740 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007741 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007742
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007743 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007744 if (I.getOpcode() == Instruction::Shl) {
7745 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7746 ShiftOp->getOpcode() == Instruction::AShr);
7747 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007748 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007749 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007750 InsertNewInstBefore(Shift, I);
7751
Reid Spencer55702aa2007-03-25 21:11:44 +00007752 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007753 return BinaryOperator::CreateAnd(Shift,
7754 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007755 }
7756
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007757 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007758 if (I.getOpcode() == Instruction::LShr) {
7759 assert(ShiftOp->getOpcode() == Instruction::Shl);
7760 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007761 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007762 InsertNewInstBefore(Shift, I);
7763
Reid Spencer68d27cf2007-03-26 23:45:51 +00007764 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007765 return BinaryOperator::CreateAnd(Shift,
7766 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007767 }
7768
7769 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007770 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007771 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007772 return 0;
7773}
7774
Chris Lattnera1be5662002-05-02 17:06:02 +00007775
Chris Lattnercfd65102005-10-29 04:36:15 +00007776/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7777/// expression. If so, decompose it, returning some value X, such that Val is
7778/// X*Scale+Offset.
7779///
7780static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007781 int &Offset, LLVMContext *Context) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007782 assert(Val->getType() == Type::getInt32Ty(*Context) && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007783 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007784 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007785 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007786 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007787 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7788 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7789 if (I->getOpcode() == Instruction::Shl) {
7790 // This is a value scaled by '1 << the shift amt'.
7791 Scale = 1U << RHS->getZExtValue();
7792 Offset = 0;
7793 return I->getOperand(0);
7794 } else if (I->getOpcode() == Instruction::Mul) {
7795 // This value is scaled by 'RHS'.
7796 Scale = RHS->getZExtValue();
7797 Offset = 0;
7798 return I->getOperand(0);
7799 } else if (I->getOpcode() == Instruction::Add) {
7800 // We have X+C. Check to see if we really have (X*C2)+C1,
7801 // where C1 is divisible by C2.
7802 unsigned SubScale;
7803 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007804 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7805 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007806 Offset += RHS->getZExtValue();
7807 Scale = SubScale;
7808 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007809 }
7810 }
7811 }
7812
7813 // Otherwise, we can't look past this.
7814 Scale = 1;
7815 Offset = 0;
7816 return Val;
7817}
7818
7819
Chris Lattnerb3f83972005-10-24 06:03:58 +00007820/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7821/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007822Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007823 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007824 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007825
Chris Lattnerb53c2382005-10-24 06:22:12 +00007826 // Remove any uses of AI that are dead.
7827 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007828
Chris Lattnerb53c2382005-10-24 06:22:12 +00007829 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7830 Instruction *User = cast<Instruction>(*UI++);
7831 if (isInstructionTriviallyDead(User)) {
7832 while (UI != E && *UI == User)
7833 ++UI; // If this instruction uses AI more than once, don't break UI.
7834
Chris Lattnerb53c2382005-10-24 06:22:12 +00007835 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007836 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007837 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007838 }
7839 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007840
7841 // This requires TargetData to get the alloca alignment and size information.
7842 if (!TD) return 0;
7843
Chris Lattnerb3f83972005-10-24 06:03:58 +00007844 // Get the type really allocated and the type casted to.
7845 const Type *AllocElTy = AI.getAllocatedType();
7846 const Type *CastElTy = PTy->getElementType();
7847 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007848
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007849 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7850 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007851 if (CastElTyAlign < AllocElTyAlign) return 0;
7852
Chris Lattner39387a52005-10-24 06:35:18 +00007853 // If the allocation has multiple uses, only promote it if we are strictly
7854 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007855 // same, we open the door to infinite loops of various kinds. (A reference
7856 // from a dbg.declare doesn't count as a use for this purpose.)
7857 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7858 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007859
Duncan Sands777d2302009-05-09 07:06:46 +00007860 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7861 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007862 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007863
Chris Lattner455fcc82005-10-29 03:19:53 +00007864 // See if we can satisfy the modulus by pulling a scale out of the array
7865 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007866 unsigned ArraySizeScale;
7867 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007868 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007869 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7870 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007871
Chris Lattner455fcc82005-10-29 03:19:53 +00007872 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7873 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007874 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7875 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007876
Chris Lattner455fcc82005-10-29 03:19:53 +00007877 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7878 Value *Amt = 0;
7879 if (Scale == 1) {
7880 Amt = NumElements;
7881 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007882 // If the allocation size is constant, form a constant mul expression
Owen Anderson1d0be152009-08-13 21:58:54 +00007883 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Reid Spencerc5b206b2006-12-31 05:48:39 +00007884 if (isa<ConstantInt>(NumElements))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007885 Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
Dan Gohman6de29f82009-06-15 22:12:54 +00007886 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007887 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007888 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007889 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007890 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007891 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007892 }
7893
Jeff Cohen86796be2007-04-04 16:58:57 +00007894 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007895 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007896 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007897 Amt = InsertNewInstBefore(Tmp, AI);
7898 }
7899
Chris Lattnerb3f83972005-10-24 06:03:58 +00007900 AllocationInst *New;
7901 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +00007902 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007903 else
Owen Anderson50dead02009-07-15 23:53:25 +00007904 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007905 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007906 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007907
Dale Johannesena0a66372009-03-05 00:39:02 +00007908 // If the allocation has one real use plus a dbg.declare, just remove the
7909 // declare.
7910 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7911 EraseInstFromFunction(*DI);
7912 }
7913 // If the allocation has multiple real uses, insert a cast and change all
7914 // things that used it to use the new cast. This will also hack on CI, but it
7915 // will die soon.
7916 else if (!AI.hasOneUse()) {
Chris Lattnerc3a3e362009-08-30 06:20:05 +00007917 AddOperandsToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007918 // New is the allocation instruction, pointer typed. AI is the original
7919 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7920 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007921 InsertNewInstBefore(NewCast, AI);
7922 AI.replaceAllUsesWith(NewCast);
7923 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007924 return ReplaceInstUsesWith(CI, New);
7925}
7926
Chris Lattner70074e02006-05-13 02:06:03 +00007927/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007928/// and return it as type Ty without inserting any new casts and without
7929/// changing the computed value. This is used by code that tries to decide
7930/// whether promoting or shrinking integer operations to wider or smaller types
7931/// will allow us to eliminate a truncate or extend.
7932///
7933/// This is a truncation operation if Ty is smaller than V->getType(), or an
7934/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007935///
7936/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7937/// should return true if trunc(V) can be computed by computing V in the smaller
7938/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7939/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7940/// efficiently truncated.
7941///
7942/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7943/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7944/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007945bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007946 unsigned CastOpc,
7947 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007948 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007949 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007950 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007951
7952 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007953 if (!I) return false;
7954
Dan Gohman6de29f82009-06-15 22:12:54 +00007955 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007956
Chris Lattner951626b2007-08-02 06:11:14 +00007957 // If this is an extension or truncate, we can often eliminate it.
7958 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7959 // If this is a cast from the destination type, we can trivially eliminate
7960 // it, and this will remove a cast overall.
7961 if (I->getOperand(0)->getType() == Ty) {
7962 // If the first operand is itself a cast, and is eliminable, do not count
7963 // this as an eliminable cast. We would prefer to eliminate those two
7964 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007965 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007966 ++NumCastsRemoved;
7967 return true;
7968 }
7969 }
7970
7971 // We can't extend or shrink something that has multiple uses: doing so would
7972 // require duplicating the instruction in general, which isn't profitable.
7973 if (!I->hasOneUse()) return false;
7974
Evan Chengf35fd542009-01-15 17:01:23 +00007975 unsigned Opc = I->getOpcode();
7976 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007977 case Instruction::Add:
7978 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007979 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007980 case Instruction::And:
7981 case Instruction::Or:
7982 case Instruction::Xor:
7983 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007984 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007985 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007986 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007987 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007988
Eli Friedman070a9812009-07-13 22:46:01 +00007989 case Instruction::UDiv:
7990 case Instruction::URem: {
7991 // UDiv and URem can be truncated if all the truncated bits are zero.
7992 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7993 uint32_t BitWidth = Ty->getScalarSizeInBits();
7994 if (BitWidth < OrigBitWidth) {
7995 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7996 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7997 MaskedValueIsZero(I->getOperand(1), Mask)) {
7998 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7999 NumCastsRemoved) &&
8000 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8001 NumCastsRemoved);
8002 }
8003 }
8004 break;
8005 }
Chris Lattner46b96052006-11-29 07:18:39 +00008006 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008007 // If we are truncating the result of this SHL, and if it's a shift of a
8008 // constant amount, we can always perform a SHL in a smaller type.
8009 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008010 uint32_t BitWidth = Ty->getScalarSizeInBits();
8011 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00008012 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 break;
8017 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008018 // If this is a truncate of a logical shr, we can truncate it to a smaller
8019 // lshr iff we know that the bits we would otherwise be shifting in are
8020 // already zeros.
8021 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008022 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8023 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008024 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008025 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008026 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8027 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008028 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008029 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008030 }
8031 }
Chris Lattner46b96052006-11-29 07:18:39 +00008032 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008033 case Instruction::ZExt:
8034 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008035 case Instruction::Trunc:
8036 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008037 // can safely replace it. Note that replacing it does not reduce the number
8038 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008039 if (Opc == CastOpc)
8040 return true;
8041
8042 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008043 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008044 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008045 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008046 case Instruction::Select: {
8047 SelectInst *SI = cast<SelectInst>(I);
8048 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008049 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008050 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008051 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008052 }
Chris Lattner8114b712008-06-18 04:00:49 +00008053 case Instruction::PHI: {
8054 // We can change a phi if we can change all operands.
8055 PHINode *PN = cast<PHINode>(I);
8056 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8057 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008058 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008059 return false;
8060 return true;
8061 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008062 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008063 // TODO: Can handle more cases here.
8064 break;
8065 }
8066
8067 return false;
8068}
8069
8070/// EvaluateInDifferentType - Given an expression that
8071/// CanEvaluateInDifferentType returns true for, actually insert the code to
8072/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008073Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008074 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008075 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00008076 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00008077 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008078
8079 // Otherwise, it must be an instruction.
8080 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008081 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008082 unsigned Opc = I->getOpcode();
8083 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008084 case Instruction::Add:
8085 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008086 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008087 case Instruction::And:
8088 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008089 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008090 case Instruction::AShr:
8091 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008092 case Instruction::Shl:
8093 case Instruction::UDiv:
8094 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008095 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008096 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008097 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008098 break;
8099 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008100 case Instruction::Trunc:
8101 case Instruction::ZExt:
8102 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008103 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008104 // just return the source. There's no need to insert it because it is not
8105 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008106 if (I->getOperand(0)->getType() == Ty)
8107 return I->getOperand(0);
8108
Chris Lattner8114b712008-06-18 04:00:49 +00008109 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008110 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008111 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008112 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008113 case Instruction::Select: {
8114 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8115 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8116 Res = SelectInst::Create(I->getOperand(0), True, False);
8117 break;
8118 }
Chris Lattner8114b712008-06-18 04:00:49 +00008119 case Instruction::PHI: {
8120 PHINode *OPN = cast<PHINode>(I);
8121 PHINode *NPN = PHINode::Create(Ty);
8122 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8123 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8124 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8125 }
8126 Res = NPN;
8127 break;
8128 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008129 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008130 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008131 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008132 break;
8133 }
8134
Chris Lattner8114b712008-06-18 04:00:49 +00008135 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008136 return InsertNewInstBefore(Res, *I);
8137}
8138
Reid Spencer3da59db2006-11-27 01:05:10 +00008139/// @brief Implement the transforms common to all CastInst visitors.
8140Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008141 Value *Src = CI.getOperand(0);
8142
Dan Gohman23d9d272007-05-11 21:10:54 +00008143 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008144 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008145 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008146 if (Instruction::CastOps opc =
8147 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8148 // The first cast (CSrc) is eliminable so we need to fix up or replace
8149 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008150 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008151 }
8152 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008153
Reid Spencer3da59db2006-11-27 01:05:10 +00008154 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008155 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8156 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8157 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008158
8159 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008160 if (isa<PHINode>(Src))
8161 if (Instruction *NV = FoldOpIntoPhi(CI))
8162 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008163
Reid Spencer3da59db2006-11-27 01:05:10 +00008164 return 0;
8165}
8166
Chris Lattner46cd5a12009-01-09 05:44:56 +00008167/// FindElementAtOffset - Given a type and a constant offset, determine whether
8168/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008169/// the specified offset. If so, fill them into NewIndices and return the
8170/// resultant element type, otherwise return null.
8171static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8172 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008173 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008174 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008175 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008176 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008177
8178 // Start with the index over the outer type. Note that the type size
8179 // might be zero (even if the offset isn't zero) if the indexed type
8180 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008181 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008182 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008183 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008184 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008185 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008186
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008187 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008188 if (Offset < 0) {
8189 --FirstIdx;
8190 Offset += TySize;
8191 assert(Offset >= 0);
8192 }
8193 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8194 }
8195
Owen Andersoneed707b2009-07-24 23:12:02 +00008196 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008197
8198 // Index into the types. If we fail, set OrigBase to null.
8199 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008200 // Indexing into tail padding between struct/array elements.
8201 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008202 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008203
Chris Lattner46cd5a12009-01-09 05:44:56 +00008204 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8205 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008206 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8207 "Offset must stay within the indexed type");
8208
Chris Lattner46cd5a12009-01-09 05:44:56 +00008209 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008210 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008211
8212 Offset -= SL->getElementOffset(Elt);
8213 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008214 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008215 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008216 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008217 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008218 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008219 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008220 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008221 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008222 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008223 }
8224 }
8225
Chris Lattner3914f722009-01-24 01:00:13 +00008226 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008227}
8228
Chris Lattnerd3e28342007-04-27 17:44:50 +00008229/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8230Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8231 Value *Src = CI.getOperand(0);
8232
Chris Lattnerd3e28342007-04-27 17:44:50 +00008233 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008234 // If casting the result of a getelementptr instruction with no offset, turn
8235 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008236 if (GEP->hasAllZeroIndices()) {
8237 // Changing the cast operand is usually not a good idea but it is safe
8238 // here because the pointer operand is being replaced with another
8239 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008240 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008241 CI.setOperand(0, GEP->getOperand(0));
8242 return &CI;
8243 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008244
8245 // If the GEP has a single use, and the base pointer is a bitcast, and the
8246 // GEP computes a constant offset, see if we can convert these three
8247 // instructions into fewer. This typically happens with unions and other
8248 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008249 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008250 if (GEP->hasAllConstantIndices()) {
8251 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008252 ConstantInt *OffsetV =
8253 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008254 int64_t Offset = OffsetV->getSExtValue();
8255
8256 // Get the base pointer input of the bitcast, and the type it points to.
8257 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8258 const Type *GEPIdxTy =
8259 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008260 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008261 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008262 // If we were able to index down into an element, create the GEP
8263 // and bitcast the result. This eliminates one bitcast, potentially
8264 // two.
8265 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8266 NewIndices.begin(),
8267 NewIndices.end(), "");
8268 InsertNewInstBefore(NGEP, CI);
8269 NGEP->takeName(GEP);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008270 if (cast<GEPOperator>(GEP)->isInBounds())
8271 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner9bc14642007-04-28 00:57:34 +00008272
Chris Lattner46cd5a12009-01-09 05:44:56 +00008273 if (isa<BitCastInst>(CI))
8274 return new BitCastInst(NGEP, CI.getType());
8275 assert(isa<PtrToIntInst>(CI));
8276 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008277 }
8278 }
8279 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008280 }
8281
8282 return commonCastTransforms(CI);
8283}
8284
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008285/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8286/// type like i42. We don't want to introduce operations on random non-legal
8287/// integer types where they don't already exist in the code. In the future,
8288/// we should consider making this based off target-data, so that 32-bit targets
8289/// won't get i64 operations etc.
8290static bool isSafeIntegerType(const Type *Ty) {
8291 switch (Ty->getPrimitiveSizeInBits()) {
8292 case 8:
8293 case 16:
8294 case 32:
8295 case 64:
8296 return true;
8297 default:
8298 return false;
8299 }
8300}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008301
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008302/// commonIntCastTransforms - This function implements the common transforms
8303/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008304Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8305 if (Instruction *Result = commonCastTransforms(CI))
8306 return Result;
8307
8308 Value *Src = CI.getOperand(0);
8309 const Type *SrcTy = Src->getType();
8310 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008311 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8312 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008313
Reid Spencer3da59db2006-11-27 01:05:10 +00008314 // See if we can simplify any instructions used by the LHS whose sole
8315 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008316 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008317 return &CI;
8318
8319 // If the source isn't an instruction or has more than one use then we
8320 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008321 Instruction *SrcI = dyn_cast<Instruction>(Src);
8322 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008323 return 0;
8324
Chris Lattnerc739cd62007-03-03 05:27:34 +00008325 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008326 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008327 // Only do this if the dest type is a simple type, don't convert the
8328 // expression tree to something weird like i93 unless the source is also
8329 // strange.
8330 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008331 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8332 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008333 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008334 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008335 // eliminates the cast, so it is always a win. If this is a zero-extension,
8336 // we need to do an AND to maintain the clear top-part of the computation,
8337 // so we require that the input have eliminated at least one cast. If this
8338 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008339 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008340 bool DoXForm = false;
8341 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008342 switch (CI.getOpcode()) {
8343 default:
8344 // All the others use floating point so we shouldn't actually
8345 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008346 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008347 case Instruction::Trunc:
8348 DoXForm = true;
8349 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008350 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008351 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008352 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008353 // If it's unnecessary to issue an AND to clear the high bits, it's
8354 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008355 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008356 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8357 if (MaskedValueIsZero(TryRes, Mask))
8358 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008359
8360 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008361 if (TryI->use_empty())
8362 EraseInstFromFunction(*TryI);
8363 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008364 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008365 }
Evan Chengf35fd542009-01-15 17:01:23 +00008366 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008367 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008368 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008369 // If we do not have to emit the truncate + sext pair, then it's always
8370 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008371 //
8372 // It's not safe to eliminate the trunc + sext pair if one of the
8373 // eliminated cast is a truncate. e.g.
8374 // t2 = trunc i32 t1 to i16
8375 // t3 = sext i16 t2 to i32
8376 // !=
8377 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008378 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008379 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8380 if (NumSignBits > (DestBitSize - SrcBitSize))
8381 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008382
8383 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008384 if (TryI->use_empty())
8385 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008386 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008387 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008388 }
Evan Chengf35fd542009-01-15 17:01:23 +00008389 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008390
8391 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008392 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8393 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008394 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8395 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008396 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008397 // Just replace this cast with the result.
8398 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008399
Reid Spencer3da59db2006-11-27 01:05:10 +00008400 assert(Res->getType() == DestTy);
8401 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008402 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008403 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008404 // Just replace this cast with the result.
8405 return ReplaceInstUsesWith(CI, Res);
8406 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008407 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008408
8409 // If the high bits are already zero, just replace this cast with the
8410 // result.
8411 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8412 if (MaskedValueIsZero(Res, Mask))
8413 return ReplaceInstUsesWith(CI, Res);
8414
8415 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008416 Constant *C = ConstantInt::get(*Context,
8417 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008418 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008419 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008420 case Instruction::SExt: {
8421 // If the high bits are already filled with sign bit, just replace this
8422 // cast with the result.
8423 unsigned NumSignBits = ComputeNumSignBits(Res);
8424 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008425 return ReplaceInstUsesWith(CI, Res);
8426
Reid Spencer3da59db2006-11-27 01:05:10 +00008427 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008428 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008429 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8430 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008431 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008432 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008433 }
8434 }
8435
8436 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8437 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8438
8439 switch (SrcI->getOpcode()) {
8440 case Instruction::Add:
8441 case Instruction::Mul:
8442 case Instruction::And:
8443 case Instruction::Or:
8444 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008445 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008446 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8447 // Don't insert two casts unless at least one can be eliminated.
8448 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008449 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman65445c52009-07-13 21:45:57 +00008450 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8451 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008452 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008453 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008454 }
8455 }
8456
8457 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8458 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8459 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008460 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008461 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008462 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008463 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008464 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008465 }
8466 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008467
Eli Friedman65445c52009-07-13 21:45:57 +00008468 case Instruction::Shl: {
8469 // Canonicalize trunc inside shl, if we can.
8470 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8471 if (CI && DestBitSize < SrcBitSize &&
8472 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8473 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8474 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008475 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008476 }
8477 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008478 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008479 }
8480 return 0;
8481}
8482
Chris Lattner8a9f5712007-04-11 06:57:46 +00008483Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008484 if (Instruction *Result = commonIntCastTransforms(CI))
8485 return Result;
8486
8487 Value *Src = CI.getOperand(0);
8488 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008489 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8490 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008491
8492 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008493 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008494 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008495 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersona7235ea2009-07-31 20:28:14 +00008496 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008497 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008498 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008499
Chris Lattner4f9797d2009-03-24 18:15:30 +00008500 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8501 ConstantInt *ShAmtV = 0;
8502 Value *ShiftOp = 0;
8503 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008504 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008505 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8506
8507 // Get a mask for the bits shifting in.
8508 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8509 if (MaskedValueIsZero(ShiftOp, Mask)) {
8510 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008511 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008512
8513 // Okay, we can shrink this. Truncate the input, then return a new
8514 // shift.
8515 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008516 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008517 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008518 }
8519 }
8520
8521 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008522}
8523
Evan Chengb98a10e2008-03-24 00:21:34 +00008524/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8525/// in order to eliminate the icmp.
8526Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8527 bool DoXform) {
8528 // If we are just checking for a icmp eq of a single bit and zext'ing it
8529 // to an integer, then shift the bit to the appropriate place and then
8530 // cast to integer to avoid the comparison.
8531 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8532 const APInt &Op1CV = Op1C->getValue();
8533
8534 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8535 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8536 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8537 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8538 if (!DoXform) return ICI;
8539
8540 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008541 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008542 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008543 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008544 In->getName()+".lobit"),
8545 CI);
8546 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008547 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008548 false/*ZExt*/, "tmp", &CI);
8549
8550 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008551 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008552 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008553 In->getName()+".not"),
8554 CI);
8555 }
8556
8557 return ReplaceInstUsesWith(CI, In);
8558 }
8559
8560
8561
8562 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8563 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8564 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8565 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8566 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8567 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8568 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8569 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8570 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8571 // This only works for EQ and NE
8572 ICI->isEquality()) {
8573 // If Op1C some other power of two, convert:
8574 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8575 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8576 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8577 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8578
8579 APInt KnownZeroMask(~KnownZero);
8580 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8581 if (!DoXform) return ICI;
8582
8583 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8584 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8585 // (X&4) == 2 --> false
8586 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008587 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008588 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008589 return ReplaceInstUsesWith(CI, Res);
8590 }
8591
8592 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8593 Value *In = ICI->getOperand(0);
8594 if (ShiftAmt) {
8595 // Perform a logical shr by shiftamt.
8596 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008597 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersoneed707b2009-07-24 23:12:02 +00008598 ConstantInt::get(In->getType(), ShiftAmt),
Evan Chengb98a10e2008-03-24 00:21:34 +00008599 In->getName()+".lobit"), CI);
8600 }
8601
8602 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008603 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008604 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008605 InsertNewInstBefore(cast<Instruction>(In), CI);
8606 }
8607
8608 if (CI.getType() == In->getType())
8609 return ReplaceInstUsesWith(CI, In);
8610 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008611 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008612 }
8613 }
8614 }
8615
8616 return 0;
8617}
8618
Chris Lattner8a9f5712007-04-11 06:57:46 +00008619Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008620 // If one of the common conversion will work ..
8621 if (Instruction *Result = commonIntCastTransforms(CI))
8622 return Result;
8623
8624 Value *Src = CI.getOperand(0);
8625
Chris Lattnera84f47c2009-02-17 20:47:23 +00008626 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8627 // types and if the sizes are just right we can convert this into a logical
8628 // 'and' which will be much cheaper than the pair of casts.
8629 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8630 // Get the sizes of the types involved. We know that the intermediate type
8631 // will be smaller than A or C, but don't know the relation between A and C.
8632 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008633 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8634 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8635 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008636 // If we're actually extending zero bits, then if
8637 // SrcSize < DstSize: zext(a & mask)
8638 // SrcSize == DstSize: a & mask
8639 // SrcSize > DstSize: trunc(a) & mask
8640 if (SrcSize < DstSize) {
8641 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008642 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008643 Instruction *And =
8644 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8645 InsertNewInstBefore(And, CI);
8646 return new ZExtInst(And, CI.getType());
8647 } else if (SrcSize == DstSize) {
8648 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008649 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008650 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008651 } else if (SrcSize > DstSize) {
8652 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8653 InsertNewInstBefore(Trunc, CI);
8654 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008655 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008656 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008657 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008658 }
8659 }
8660
Evan Chengb98a10e2008-03-24 00:21:34 +00008661 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8662 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008663
Evan Chengb98a10e2008-03-24 00:21:34 +00008664 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8665 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8666 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8667 // of the (zext icmp) will be transformed.
8668 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8669 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8670 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8671 (transformZExtICmp(LHS, CI, false) ||
8672 transformZExtICmp(RHS, CI, false))) {
8673 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8674 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008675 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008676 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008677 }
8678
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008679 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008680 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8681 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8682 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8683 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008684 if (TI0->getType() == CI.getType())
8685 return
8686 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008687 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008688 }
8689
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008690 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8691 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8692 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8693 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8694 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8695 And->getOperand(1) == C)
8696 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8697 Value *TI0 = TI->getOperand(0);
8698 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008699 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008700 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8701 InsertNewInstBefore(NewAnd, *And);
8702 return BinaryOperator::CreateXor(NewAnd, ZC);
8703 }
8704 }
8705
Reid Spencer3da59db2006-11-27 01:05:10 +00008706 return 0;
8707}
8708
Chris Lattner8a9f5712007-04-11 06:57:46 +00008709Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008710 if (Instruction *I = commonIntCastTransforms(CI))
8711 return I;
8712
Chris Lattner8a9f5712007-04-11 06:57:46 +00008713 Value *Src = CI.getOperand(0);
8714
Dan Gohman1975d032008-10-30 20:40:10 +00008715 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008716 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008717 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008718 Constant::getAllOnesValue(CI.getType()),
8719 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008720
8721 // See if the value being truncated is already sign extended. If so, just
8722 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008723 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008724 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008725 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8726 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8727 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008728 unsigned NumSignBits = ComputeNumSignBits(Op);
8729
8730 if (OpBits == DestBits) {
8731 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8732 // bits, it is already ready.
8733 if (NumSignBits > DestBits-MidBits)
8734 return ReplaceInstUsesWith(CI, Op);
8735 } else if (OpBits < DestBits) {
8736 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8737 // bits, just sext from i32.
8738 if (NumSignBits > OpBits-MidBits)
8739 return new SExtInst(Op, CI.getType(), "tmp");
8740 } else {
8741 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8742 // bits, just truncate to i32.
8743 if (NumSignBits > OpBits-MidBits)
8744 return new TruncInst(Op, CI.getType(), "tmp");
8745 }
8746 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008747
8748 // If the input is a shl/ashr pair of a same constant, then this is a sign
8749 // extension from a smaller value. If we could trust arbitrary bitwidth
8750 // integers, we could turn this into a truncate to the smaller bit and then
8751 // use a sext for the whole extension. Since we don't, look deeper and check
8752 // for a truncate. If the source and dest are the same type, eliminate the
8753 // trunc and extend and just do shifts. For example, turn:
8754 // %a = trunc i32 %i to i8
8755 // %b = shl i8 %a, 6
8756 // %c = ashr i8 %b, 6
8757 // %d = sext i8 %c to i32
8758 // into:
8759 // %a = shl i32 %i, 30
8760 // %d = ashr i32 %a, 30
8761 Value *A = 0;
8762 ConstantInt *BA = 0, *CA = 0;
8763 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008764 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008765 BA == CA && isa<TruncInst>(A)) {
8766 Value *I = cast<TruncInst>(A)->getOperand(0);
8767 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008768 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8769 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008770 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008771 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattner46bbad22008-08-06 07:35:52 +00008772 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8773 CI.getName()), CI);
8774 return BinaryOperator::CreateAShr(I, ShAmtV);
8775 }
8776 }
8777
Chris Lattnerba417832007-04-11 06:12:58 +00008778 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008779}
8780
Chris Lattnerb7530652008-01-27 05:29:54 +00008781/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8782/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008783static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008784 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008785 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008786 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008787 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8788 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008789 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008790 return 0;
8791}
8792
8793/// LookThroughFPExtensions - If this is an fp extension instruction, look
8794/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008795static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008796 if (Instruction *I = dyn_cast<Instruction>(V))
8797 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008798 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008799
8800 // If this value is a constant, return the constant in the smallest FP type
8801 // that can accurately represent it. This allows us to turn
8802 // (float)((double)X+2.0) into x+2.0f.
8803 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008804 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008805 return V; // No constant folding of this.
8806 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008807 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008808 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008809 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008810 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008811 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008812 return V;
8813 // Don't try to shrink to various long double types.
8814 }
8815
8816 return V;
8817}
8818
8819Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8820 if (Instruction *I = commonCastTransforms(CI))
8821 return I;
8822
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008823 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008824 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008825 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008826 // many builtins (sqrt, etc).
8827 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8828 if (OpI && OpI->hasOneUse()) {
8829 switch (OpI->getOpcode()) {
8830 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008831 case Instruction::FAdd:
8832 case Instruction::FSub:
8833 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008834 case Instruction::FDiv:
8835 case Instruction::FRem:
8836 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008837 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8838 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008839 if (LHSTrunc->getType() != SrcTy &&
8840 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008841 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008842 // If the source types were both smaller than the destination type of
8843 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008844 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8845 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008846 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8847 CI.getType(), CI);
8848 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8849 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008850 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008851 }
8852 }
8853 break;
8854 }
8855 }
8856 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008857}
8858
8859Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8860 return commonCastTransforms(CI);
8861}
8862
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008863Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008864 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8865 if (OpI == 0)
8866 return commonCastTransforms(FI);
8867
8868 // fptoui(uitofp(X)) --> X
8869 // fptoui(sitofp(X)) --> X
8870 // This is safe if the intermediate type has enough bits in its mantissa to
8871 // accurately represent all values of X. For example, do not do this with
8872 // i64->float->i64. This is also safe for sitofp case, because any negative
8873 // 'X' value would cause an undefined result for the fptoui.
8874 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8875 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008876 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008877 OpI->getType()->getFPMantissaWidth())
8878 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008879
8880 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008881}
8882
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008883Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008884 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8885 if (OpI == 0)
8886 return commonCastTransforms(FI);
8887
8888 // fptosi(sitofp(X)) --> X
8889 // fptosi(uitofp(X)) --> X
8890 // This is safe if the intermediate type has enough bits in its mantissa to
8891 // accurately represent all values of X. For example, do not do this with
8892 // i64->float->i64. This is also safe for sitofp case, because any negative
8893 // 'X' value would cause an undefined result for the fptoui.
8894 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8895 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008896 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008897 OpI->getType()->getFPMantissaWidth())
8898 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008899
8900 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008901}
8902
8903Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8904 return commonCastTransforms(CI);
8905}
8906
8907Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8908 return commonCastTransforms(CI);
8909}
8910
Chris Lattnera0e69692009-03-24 18:35:40 +00008911Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8912 // If the destination integer type is smaller than the intptr_t type for
8913 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8914 // trunc to be exposed to other transforms. Don't do this for extending
8915 // ptrtoint's, because we don't know if the target sign or zero extends its
8916 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008917 if (TD &&
8918 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008919 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
Owen Anderson1d0be152009-08-13 21:58:54 +00008920 TD->getIntPtrType(CI.getContext()),
Chris Lattnera0e69692009-03-24 18:35:40 +00008921 "tmp"), CI);
8922 return new TruncInst(P, CI.getType());
8923 }
8924
Chris Lattnerd3e28342007-04-27 17:44:50 +00008925 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008926}
8927
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008928Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008929 // If the source integer type is larger than the intptr_t type for
8930 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8931 // allows the trunc to be exposed to other transforms. Don't do this for
8932 // extending inttoptr's, because we don't know if the target sign or zero
8933 // extends to pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008934 if (TD &&
8935 CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008936 TD->getPointerSizeInBits()) {
8937 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
Owen Anderson1d0be152009-08-13 21:58:54 +00008938 TD->getIntPtrType(CI.getContext()),
Chris Lattnera0e69692009-03-24 18:35:40 +00008939 "tmp"), CI);
8940 return new IntToPtrInst(P, CI.getType());
8941 }
8942
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008943 if (Instruction *I = commonCastTransforms(CI))
8944 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008945
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008946 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008947}
8948
Chris Lattnerd3e28342007-04-27 17:44:50 +00008949Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008950 // If the operands are integer typed then apply the integer transforms,
8951 // otherwise just apply the common ones.
8952 Value *Src = CI.getOperand(0);
8953 const Type *SrcTy = Src->getType();
8954 const Type *DestTy = CI.getType();
8955
Eli Friedman7e25d452009-07-13 20:53:00 +00008956 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008957 if (Instruction *I = commonPointerCastTransforms(CI))
8958 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008959 } else {
8960 if (Instruction *Result = commonCastTransforms(CI))
8961 return Result;
8962 }
8963
8964
8965 // Get rid of casts from one type to the same type. These are useless and can
8966 // be replaced by the operand.
8967 if (DestTy == Src->getType())
8968 return ReplaceInstUsesWith(CI, Src);
8969
Reid Spencer3da59db2006-11-27 01:05:10 +00008970 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008971 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8972 const Type *DstElTy = DstPTy->getElementType();
8973 const Type *SrcElTy = SrcPTy->getElementType();
8974
Nate Begeman83ad90a2008-03-31 00:22:16 +00008975 // If the address spaces don't match, don't eliminate the bitcast, which is
8976 // required for changing types.
8977 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8978 return 0;
8979
Chris Lattnerd3e28342007-04-27 17:44:50 +00008980 // If we are casting a malloc or alloca to a pointer to a type of the same
8981 // size, rewrite the allocation instruction to allocate the "right" type.
8982 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8983 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8984 return V;
8985
Chris Lattnerd717c182007-05-05 22:32:24 +00008986 // If the source and destination are pointers, and this cast is equivalent
8987 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008988 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008989 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008990 unsigned NumZeros = 0;
8991 while (SrcElTy != DstElTy &&
8992 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8993 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8994 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8995 ++NumZeros;
8996 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008997
Chris Lattnerd3e28342007-04-27 17:44:50 +00008998 // If we found a path from the src to dest, create the getelementptr now.
8999 if (SrcElTy == DstElTy) {
9000 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00009001 Instruction *GEP = GetElementPtrInst::Create(Src,
9002 Idxs.begin(), Idxs.end(), "",
9003 ((Instruction*) NULL));
9004 cast<GEPOperator>(GEP)->setIsInBounds(true);
9005 return GEP;
Chris Lattner9fb92132006-04-12 18:09:35 +00009006 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009007 }
Chris Lattner24c8e382003-07-24 17:35:25 +00009008
Eli Friedman2451a642009-07-18 23:06:53 +00009009 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9010 if (DestVTy->getNumElements() == 1) {
9011 if (!isa<VectorType>(SrcTy)) {
9012 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
9013 DestVTy->getElementType(), CI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009014 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Owen Anderson1d0be152009-08-13 21:58:54 +00009015 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009016 }
9017 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9018 }
9019 }
9020
9021 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9022 if (SrcVTy->getNumElements() == 1) {
9023 if (!isa<VectorType>(DestTy)) {
9024 Instruction *Elem =
Owen Anderson1d0be152009-08-13 21:58:54 +00009025 ExtractElementInst::Create(Src, Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009026 InsertNewInstBefore(Elem, CI);
9027 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9028 }
9029 }
9030 }
9031
Reid Spencer3da59db2006-11-27 01:05:10 +00009032 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9033 if (SVI->hasOneUse()) {
9034 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9035 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009036 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009037 cast<VectorType>(DestTy)->getNumElements() ==
9038 SVI->getType()->getNumElements() &&
9039 SVI->getType()->getNumElements() ==
9040 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009041 CastInst *Tmp;
9042 // If either of the operands is a cast from CI.getType(), then
9043 // evaluating the shuffle in the casted destination's type will allow
9044 // us to eliminate at least one cast.
9045 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9046 Tmp->getOperand(0)->getType() == DestTy) ||
9047 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9048 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009049 Value *LHS = InsertCastBefore(Instruction::BitCast,
9050 SVI->getOperand(0), DestTy, CI);
9051 Value *RHS = InsertCastBefore(Instruction::BitCast,
9052 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009053 // Return a new shuffle vector. Use the same element ID's, as we
9054 // know the vector types match #elts.
9055 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009056 }
9057 }
9058 }
9059 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009060 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009061}
9062
Chris Lattnere576b912004-04-09 23:46:01 +00009063/// GetSelectFoldableOperands - We want to turn code that looks like this:
9064/// %C = or %A, %B
9065/// %D = select %cond, %C, %A
9066/// into:
9067/// %C = select %cond, %B, 0
9068/// %D = or %A, %C
9069///
9070/// Assuming that the specified instruction is an operand to the select, return
9071/// a bitmask indicating which operands of this instruction are foldable if they
9072/// equal the other incoming value of the select.
9073///
9074static unsigned GetSelectFoldableOperands(Instruction *I) {
9075 switch (I->getOpcode()) {
9076 case Instruction::Add:
9077 case Instruction::Mul:
9078 case Instruction::And:
9079 case Instruction::Or:
9080 case Instruction::Xor:
9081 return 3; // Can fold through either operand.
9082 case Instruction::Sub: // Can only fold on the amount subtracted.
9083 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009084 case Instruction::LShr:
9085 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009086 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009087 default:
9088 return 0; // Cannot fold
9089 }
9090}
9091
9092/// GetSelectFoldableConstant - For the same transformation as the previous
9093/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009094static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009095 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009096 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009097 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009098 case Instruction::Add:
9099 case Instruction::Sub:
9100 case Instruction::Or:
9101 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009102 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009103 case Instruction::LShr:
9104 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009105 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009106 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009107 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009108 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009109 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009110 }
9111}
9112
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009113/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9114/// have the same opcode and only one use each. Try to simplify this.
9115Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9116 Instruction *FI) {
9117 if (TI->getNumOperands() == 1) {
9118 // If this is a non-volatile load or a cast from the same type,
9119 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009120 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009121 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9122 return 0;
9123 } else {
9124 return 0; // unknown unary op.
9125 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009126
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009127 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009128 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009129 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009130 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009131 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009132 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009133 }
9134
Reid Spencer832254e2007-02-02 02:16:23 +00009135 // Only handle binary operators here.
9136 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009137 return 0;
9138
9139 // Figure out if the operations have any operands in common.
9140 Value *MatchOp, *OtherOpT, *OtherOpF;
9141 bool MatchIsOpZero;
9142 if (TI->getOperand(0) == FI->getOperand(0)) {
9143 MatchOp = TI->getOperand(0);
9144 OtherOpT = TI->getOperand(1);
9145 OtherOpF = FI->getOperand(1);
9146 MatchIsOpZero = true;
9147 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9148 MatchOp = TI->getOperand(1);
9149 OtherOpT = TI->getOperand(0);
9150 OtherOpF = FI->getOperand(0);
9151 MatchIsOpZero = false;
9152 } else if (!TI->isCommutative()) {
9153 return 0;
9154 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9155 MatchOp = TI->getOperand(0);
9156 OtherOpT = TI->getOperand(1);
9157 OtherOpF = FI->getOperand(0);
9158 MatchIsOpZero = true;
9159 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9160 MatchOp = TI->getOperand(1);
9161 OtherOpT = TI->getOperand(0);
9162 OtherOpF = FI->getOperand(1);
9163 MatchIsOpZero = true;
9164 } else {
9165 return 0;
9166 }
9167
9168 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009169 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9170 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009171 InsertNewInstBefore(NewSI, SI);
9172
9173 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9174 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009175 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009176 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009177 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009178 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009179 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009180 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009181}
9182
Evan Chengde621922009-03-31 20:42:45 +00009183static bool isSelect01(Constant *C1, Constant *C2) {
9184 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9185 if (!C1I)
9186 return false;
9187 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9188 if (!C2I)
9189 return false;
9190 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9191}
9192
9193/// FoldSelectIntoOp - Try fold the select into one of the operands to
9194/// facilitate further optimization.
9195Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9196 Value *FalseVal) {
9197 // See the comment above GetSelectFoldableOperands for a description of the
9198 // transformation we are doing here.
9199 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9200 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9201 !isa<Constant>(FalseVal)) {
9202 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9203 unsigned OpToFold = 0;
9204 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9205 OpToFold = 1;
9206 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9207 OpToFold = 2;
9208 }
9209
9210 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009211 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009212 Value *OOp = TVI->getOperand(2-OpToFold);
9213 // Avoid creating select between 2 constants unless it's selecting
9214 // between 0 and 1.
9215 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9216 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9217 InsertNewInstBefore(NewSel, SI);
9218 NewSel->takeName(TVI);
9219 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9220 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009221 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009222 }
9223 }
9224 }
9225 }
9226 }
9227
9228 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9229 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9230 !isa<Constant>(TrueVal)) {
9231 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9232 unsigned OpToFold = 0;
9233 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9234 OpToFold = 1;
9235 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9236 OpToFold = 2;
9237 }
9238
9239 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009240 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009241 Value *OOp = FVI->getOperand(2-OpToFold);
9242 // Avoid creating select between 2 constants unless it's selecting
9243 // between 0 and 1.
9244 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9245 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9246 InsertNewInstBefore(NewSel, SI);
9247 NewSel->takeName(FVI);
9248 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9249 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009250 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009251 }
9252 }
9253 }
9254 }
9255 }
9256
9257 return 0;
9258}
9259
Dan Gohman81b28ce2008-09-16 18:46:06 +00009260/// visitSelectInstWithICmp - Visit a SelectInst that has an
9261/// ICmpInst as its first operand.
9262///
9263Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9264 ICmpInst *ICI) {
9265 bool Changed = false;
9266 ICmpInst::Predicate Pred = ICI->getPredicate();
9267 Value *CmpLHS = ICI->getOperand(0);
9268 Value *CmpRHS = ICI->getOperand(1);
9269 Value *TrueVal = SI.getTrueValue();
9270 Value *FalseVal = SI.getFalseValue();
9271
9272 // Check cases where the comparison is with a constant that
9273 // can be adjusted to fit the min/max idiom. We may edit ICI in
9274 // place here, so make sure the select is the only user.
9275 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009276 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009277 switch (Pred) {
9278 default: break;
9279 case ICmpInst::ICMP_ULT:
9280 case ICmpInst::ICMP_SLT: {
9281 // X < MIN ? T : F --> F
9282 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9283 return ReplaceInstUsesWith(SI, FalseVal);
9284 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009285 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009286 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9287 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9288 Pred = ICmpInst::getSwappedPredicate(Pred);
9289 CmpRHS = AdjustedRHS;
9290 std::swap(FalseVal, TrueVal);
9291 ICI->setPredicate(Pred);
9292 ICI->setOperand(1, CmpRHS);
9293 SI.setOperand(1, TrueVal);
9294 SI.setOperand(2, FalseVal);
9295 Changed = true;
9296 }
9297 break;
9298 }
9299 case ICmpInst::ICMP_UGT:
9300 case ICmpInst::ICMP_SGT: {
9301 // X > MAX ? T : F --> F
9302 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9303 return ReplaceInstUsesWith(SI, FalseVal);
9304 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009305 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009306 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9307 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9308 Pred = ICmpInst::getSwappedPredicate(Pred);
9309 CmpRHS = AdjustedRHS;
9310 std::swap(FalseVal, TrueVal);
9311 ICI->setPredicate(Pred);
9312 ICI->setOperand(1, CmpRHS);
9313 SI.setOperand(1, TrueVal);
9314 SI.setOperand(2, FalseVal);
9315 Changed = true;
9316 }
9317 break;
9318 }
9319 }
9320
Dan Gohman1975d032008-10-30 20:40:10 +00009321 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9322 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009323 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009324 if (match(TrueVal, m_ConstantInt<-1>()) &&
9325 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009326 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009327 else if (match(TrueVal, m_ConstantInt<0>()) &&
9328 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009329 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9330
Dan Gohman1975d032008-10-30 20:40:10 +00009331 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9332 // If we are just checking for a icmp eq of a single bit and zext'ing it
9333 // to an integer, then shift the bit to the appropriate place and then
9334 // cast to integer to avoid the comparison.
9335 const APInt &Op1CV = CI->getValue();
9336
9337 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9338 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9339 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009340 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009341 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009342 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009343 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009344 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009345 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009346 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009347 if (In->getType() != SI.getType())
9348 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009349 true/*SExt*/, "tmp", ICI);
9350
9351 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009352 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009353 In->getName()+".not"), *ICI);
9354
9355 return ReplaceInstUsesWith(SI, In);
9356 }
9357 }
9358 }
9359
Dan Gohman81b28ce2008-09-16 18:46:06 +00009360 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9361 // Transform (X == Y) ? X : Y -> Y
9362 if (Pred == ICmpInst::ICMP_EQ)
9363 return ReplaceInstUsesWith(SI, FalseVal);
9364 // Transform (X != Y) ? X : Y -> X
9365 if (Pred == ICmpInst::ICMP_NE)
9366 return ReplaceInstUsesWith(SI, TrueVal);
9367 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9368
9369 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9370 // Transform (X == Y) ? Y : X -> X
9371 if (Pred == ICmpInst::ICMP_EQ)
9372 return ReplaceInstUsesWith(SI, FalseVal);
9373 // Transform (X != Y) ? Y : X -> Y
9374 if (Pred == ICmpInst::ICMP_NE)
9375 return ReplaceInstUsesWith(SI, TrueVal);
9376 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9377 }
9378
9379 /// NOTE: if we wanted to, this is where to detect integer ABS
9380
9381 return Changed ? &SI : 0;
9382}
9383
Chris Lattner3d69f462004-03-12 05:52:32 +00009384Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009385 Value *CondVal = SI.getCondition();
9386 Value *TrueVal = SI.getTrueValue();
9387 Value *FalseVal = SI.getFalseValue();
9388
9389 // select true, X, Y -> X
9390 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009391 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009392 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009393
9394 // select C, X, X -> X
9395 if (TrueVal == FalseVal)
9396 return ReplaceInstUsesWith(SI, TrueVal);
9397
Chris Lattnere87597f2004-10-16 18:11:37 +00009398 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9399 return ReplaceInstUsesWith(SI, FalseVal);
9400 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9401 return ReplaceInstUsesWith(SI, TrueVal);
9402 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9403 if (isa<Constant>(TrueVal))
9404 return ReplaceInstUsesWith(SI, TrueVal);
9405 else
9406 return ReplaceInstUsesWith(SI, FalseVal);
9407 }
9408
Owen Anderson1d0be152009-08-13 21:58:54 +00009409 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009410 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009411 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009412 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009413 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009414 } else {
9415 // Change: A = select B, false, C --> A = and !B, C
9416 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009417 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009418 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009419 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009420 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009421 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009422 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009423 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009424 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009425 } else {
9426 // Change: A = select B, C, true --> A = or !B, C
9427 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009428 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009429 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009430 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009431 }
9432 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009433
9434 // select a, b, a -> a&b
9435 // select a, a, b -> a|b
9436 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009437 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009438 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009439 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009440 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009441
Chris Lattner2eefe512004-04-09 19:05:30 +00009442 // Selecting between two integer constants?
9443 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9444 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009445 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009446 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009447 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009448 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009449 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009450 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009451 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009452 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009453 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009454 }
Chris Lattner457dd822004-06-09 07:59:58 +00009455
Reid Spencere4d87aa2006-12-23 06:05:41 +00009456 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009457 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009458 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009459 // non-constant value, eliminate this whole mess. This corresponds to
9460 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009461 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009462 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009463 cast<Constant>(IC->getOperand(1))->isNullValue())
9464 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9465 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009466 isa<ConstantInt>(ICA->getOperand(1)) &&
9467 (ICA->getOperand(1) == TrueValC ||
9468 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009469 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9470 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009471 // know whether we have a icmp_ne or icmp_eq and whether the
9472 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009473 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009474 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009475 Value *V = ICA;
9476 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009477 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009478 Instruction::Xor, V, ICA->getOperand(1)), SI);
9479 return ReplaceInstUsesWith(SI, V);
9480 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009481 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009482 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009483
9484 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009485 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9486 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009487 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009488 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9489 // This is not safe in general for floating point:
9490 // consider X== -0, Y== +0.
9491 // It becomes safe if either operand is a nonzero constant.
9492 ConstantFP *CFPt, *CFPf;
9493 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9494 !CFPt->getValueAPF().isZero()) ||
9495 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9496 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009497 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009498 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009499 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009500 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009501 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009502 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009503
Reid Spencere4d87aa2006-12-23 06:05:41 +00009504 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009505 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009506 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9507 // This is not safe in general for floating point:
9508 // consider X== -0, Y== +0.
9509 // It becomes safe if either operand is a nonzero constant.
9510 ConstantFP *CFPt, *CFPf;
9511 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9512 !CFPt->getValueAPF().isZero()) ||
9513 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9514 !CFPf->getValueAPF().isZero()))
9515 return ReplaceInstUsesWith(SI, FalseVal);
9516 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009517 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009518 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9519 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009520 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009521 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009522 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009523 }
9524
9525 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009526 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9527 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9528 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009529
Chris Lattner87875da2005-01-13 22:52:24 +00009530 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9531 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9532 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009533 Instruction *AddOp = 0, *SubOp = 0;
9534
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009535 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9536 if (TI->getOpcode() == FI->getOpcode())
9537 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9538 return IV;
9539
9540 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9541 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009542 if ((TI->getOpcode() == Instruction::Sub &&
9543 FI->getOpcode() == Instruction::Add) ||
9544 (TI->getOpcode() == Instruction::FSub &&
9545 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009546 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009547 } else if ((FI->getOpcode() == Instruction::Sub &&
9548 TI->getOpcode() == Instruction::Add) ||
9549 (FI->getOpcode() == Instruction::FSub &&
9550 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009551 AddOp = TI; SubOp = FI;
9552 }
9553
9554 if (AddOp) {
9555 Value *OtherAddOp = 0;
9556 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9557 OtherAddOp = AddOp->getOperand(1);
9558 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9559 OtherAddOp = AddOp->getOperand(0);
9560 }
9561
9562 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009563 // So at this point we know we have (Y -> OtherAddOp):
9564 // select C, (add X, Y), (sub X, Z)
9565 Value *NegVal; // Compute -Z
9566 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009567 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009568 } else {
9569 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009570 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009571 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009572 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009573
9574 Value *NewTrueOp = OtherAddOp;
9575 Value *NewFalseOp = NegVal;
9576 if (AddOp != TI)
9577 std::swap(NewTrueOp, NewFalseOp);
9578 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009579 SelectInst::Create(CondVal, NewTrueOp,
9580 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009581
9582 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009583 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009584 }
9585 }
9586 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009587
Chris Lattnere576b912004-04-09 23:46:01 +00009588 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009589 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009590 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9591 if (FoldI)
9592 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009593 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009594
9595 if (BinaryOperator::isNot(CondVal)) {
9596 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9597 SI.setOperand(1, FalseVal);
9598 SI.setOperand(2, TrueVal);
9599 return &SI;
9600 }
9601
Chris Lattner3d69f462004-03-12 05:52:32 +00009602 return 0;
9603}
9604
Dan Gohmaneee962e2008-04-10 18:43:06 +00009605/// EnforceKnownAlignment - If the specified pointer points to an object that
9606/// we control, modify the object's alignment to PrefAlign. This isn't
9607/// often possible though. If alignment is important, a more reliable approach
9608/// is to simply align all global variables and allocation instructions to
9609/// their preferred alignment from the beginning.
9610///
9611static unsigned EnforceKnownAlignment(Value *V,
9612 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009613
Dan Gohmaneee962e2008-04-10 18:43:06 +00009614 User *U = dyn_cast<User>(V);
9615 if (!U) return Align;
9616
Dan Gohmanca178902009-07-17 20:47:02 +00009617 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009618 default: break;
9619 case Instruction::BitCast:
9620 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9621 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009622 // If all indexes are zero, it is just the alignment of the base pointer.
9623 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009624 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009625 if (!isa<Constant>(*i) ||
9626 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009627 AllZeroOperands = false;
9628 break;
9629 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009630
9631 if (AllZeroOperands) {
9632 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009633 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009634 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009635 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009636 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009637 }
9638
9639 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9640 // If there is a large requested alignment and we can, bump up the alignment
9641 // of the global.
9642 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009643 if (GV->getAlignment() >= PrefAlign)
9644 Align = GV->getAlignment();
9645 else {
9646 GV->setAlignment(PrefAlign);
9647 Align = PrefAlign;
9648 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009649 }
9650 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9651 // If there is a requested alignment and if this is an alloca, round up. We
9652 // don't do this for malloc, because some systems can't respect the request.
9653 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009654 if (AI->getAlignment() >= PrefAlign)
9655 Align = AI->getAlignment();
9656 else {
9657 AI->setAlignment(PrefAlign);
9658 Align = PrefAlign;
9659 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009660 }
9661 }
9662
9663 return Align;
9664}
9665
9666/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9667/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9668/// and it is more than the alignment of the ultimate object, see if we can
9669/// increase the alignment of the ultimate object, making this check succeed.
9670unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9671 unsigned PrefAlign) {
9672 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9673 sizeof(PrefAlign) * CHAR_BIT;
9674 APInt Mask = APInt::getAllOnesValue(BitWidth);
9675 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9676 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9677 unsigned TrailZ = KnownZero.countTrailingOnes();
9678 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9679
9680 if (PrefAlign > Align)
9681 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9682
9683 // We don't need to make any adjustment.
9684 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009685}
9686
Chris Lattnerf497b022008-01-13 23:50:23 +00009687Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009688 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009689 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009690 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009691 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009692
9693 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009694 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009695 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009696 return MI;
9697 }
9698
9699 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9700 // load/store.
9701 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9702 if (MemOpLength == 0) return 0;
9703
Chris Lattner37ac6082008-01-14 00:28:35 +00009704 // Source and destination pointer types are always "i8*" for intrinsic. See
9705 // if the size is something we can handle with a single primitive load/store.
9706 // A single load+store correctly handles overlapping memory in the memmove
9707 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009708 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009709 if (Size == 0) return MI; // Delete this mem transfer.
9710
9711 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009712 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009713
Chris Lattner37ac6082008-01-14 00:28:35 +00009714 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009715 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009716 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009717
9718 // Memcpy forces the use of i8* for the source and destination. That means
9719 // that if you're using memcpy to move one double around, you'll get a cast
9720 // from double* to i8*. We'd much rather use a double load+store rather than
9721 // an i64 load+store, here because this improves the odds that the source or
9722 // dest address will be promotable. See if we can find a better type than the
9723 // integer datatype.
9724 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9725 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009726 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009727 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9728 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009729 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009730 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9731 if (STy->getNumElements() == 1)
9732 SrcETy = STy->getElementType(0);
9733 else
9734 break;
9735 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9736 if (ATy->getNumElements() == 1)
9737 SrcETy = ATy->getElementType();
9738 else
9739 break;
9740 } else
9741 break;
9742 }
9743
Dan Gohman8f8e2692008-05-23 01:52:21 +00009744 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009745 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009746 }
9747 }
9748
9749
Chris Lattnerf497b022008-01-13 23:50:23 +00009750 // If the memcpy/memmove provides better alignment info than we can
9751 // infer, use it.
9752 SrcAlign = std::max(SrcAlign, CopyAlign);
9753 DstAlign = std::max(DstAlign, CopyAlign);
9754
9755 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9756 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009757 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9758 InsertNewInstBefore(L, *MI);
9759 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9760
9761 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009762 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009763 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009764}
Chris Lattner3d69f462004-03-12 05:52:32 +00009765
Chris Lattner69ea9d22008-04-30 06:39:11 +00009766Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9767 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009768 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009769 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009770 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009771 return MI;
9772 }
9773
9774 // Extract the length and alignment and fill if they are constant.
9775 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9776 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009777 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009778 return 0;
9779 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009780 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009781
9782 // If the length is zero, this is a no-op
9783 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9784
9785 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9786 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009787 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009788
9789 Value *Dest = MI->getDest();
Owen Andersondebcb012009-07-29 22:17:13 +00009790 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009791
9792 // Alignment 0 is identity for alignment 1 for memset, but not store.
9793 if (Alignment == 0) Alignment = 1;
9794
9795 // Extract the fill value and store.
9796 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009797 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009798 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009799
9800 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009801 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009802 return MI;
9803 }
9804
9805 return 0;
9806}
9807
9808
Chris Lattner8b0ea312006-01-13 20:11:04 +00009809/// visitCallInst - CallInst simplification. This mostly only handles folding
9810/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9811/// the heavy lifting.
9812///
Chris Lattner9fe38862003-06-19 17:00:31 +00009813Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009814 // If the caller function is nounwind, mark the call as nounwind, even if the
9815 // callee isn't.
9816 if (CI.getParent()->getParent()->doesNotThrow() &&
9817 !CI.doesNotThrow()) {
9818 CI.setDoesNotThrow();
9819 return &CI;
9820 }
9821
9822
9823
Chris Lattner8b0ea312006-01-13 20:11:04 +00009824 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9825 if (!II) return visitCallSite(&CI);
9826
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009827 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9828 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009829 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009830 bool Changed = false;
9831
9832 // memmove/cpy/set of zero bytes is a noop.
9833 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9834 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9835
Chris Lattner35b9e482004-10-12 04:52:52 +00009836 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009837 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009838 // Replace the instruction with just byte operations. We would
9839 // transform other cases to loads/stores, but we don't know if
9840 // alignment is sufficient.
9841 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009842 }
9843
Chris Lattner35b9e482004-10-12 04:52:52 +00009844 // If we have a memmove and the source operation is a constant global,
9845 // then the source and dest pointers can't alias, so we can change this
9846 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009847 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009848 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9849 if (GVSrc->isConstant()) {
9850 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009851 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9852 const Type *Tys[1];
9853 Tys[0] = CI.getOperand(3)->getType();
9854 CI.setOperand(0,
9855 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009856 Changed = true;
9857 }
Chris Lattnera935db82008-05-28 05:30:41 +00009858
9859 // memmove(x,x,size) -> noop.
9860 if (MMI->getSource() == MMI->getDest())
9861 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009862 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009863
Chris Lattner95a959d2006-03-06 20:18:44 +00009864 // If we can determine a pointer alignment that is bigger than currently
9865 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009866 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009867 if (Instruction *I = SimplifyMemTransfer(MI))
9868 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009869 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9870 if (Instruction *I = SimplifyMemSet(MSI))
9871 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009872 }
9873
Chris Lattner8b0ea312006-01-13 20:11:04 +00009874 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009875 }
9876
9877 switch (II->getIntrinsicID()) {
9878 default: break;
9879 case Intrinsic::bswap:
9880 // bswap(bswap(x)) -> x
9881 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9882 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9883 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9884 break;
9885 case Intrinsic::ppc_altivec_lvx:
9886 case Intrinsic::ppc_altivec_lvxl:
9887 case Intrinsic::x86_sse_loadu_ps:
9888 case Intrinsic::x86_sse2_loadu_pd:
9889 case Intrinsic::x86_sse2_loadu_dq:
9890 // Turn PPC lvx -> load if the pointer is known aligned.
9891 // Turn X86 loadups -> load if the pointer is known aligned.
9892 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9893 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersondebcb012009-07-29 22:17:13 +00009894 PointerType::getUnqual(II->getType()),
Chris Lattner0521e3c2008-06-18 04:33:20 +00009895 CI);
9896 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009897 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009898 break;
9899 case Intrinsic::ppc_altivec_stvx:
9900 case Intrinsic::ppc_altivec_stvxl:
9901 // Turn stvx -> store if the pointer is known aligned.
9902 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9903 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009904 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009905 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9906 return new StoreInst(II->getOperand(1), Ptr);
9907 }
9908 break;
9909 case Intrinsic::x86_sse_storeu_ps:
9910 case Intrinsic::x86_sse2_storeu_pd:
9911 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009912 // Turn X86 storeu -> store if the pointer is known aligned.
9913 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9914 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009915 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009916 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9917 return new StoreInst(II->getOperand(2), Ptr);
9918 }
9919 break;
9920
9921 case Intrinsic::x86_sse_cvttss2si: {
9922 // These intrinsics only demands the 0th element of its input vector. If
9923 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009924 unsigned VWidth =
9925 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9926 APInt DemandedElts(VWidth, 1);
9927 APInt UndefElts(VWidth, 0);
9928 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009929 UndefElts)) {
9930 II->setOperand(1, V);
9931 return II;
9932 }
9933 break;
9934 }
9935
9936 case Intrinsic::ppc_altivec_vperm:
9937 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9938 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9939 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009940
Chris Lattner0521e3c2008-06-18 04:33:20 +00009941 // Check that all of the elements are integer constants or undefs.
9942 bool AllEltsOk = true;
9943 for (unsigned i = 0; i != 16; ++i) {
9944 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9945 !isa<UndefValue>(Mask->getOperand(i))) {
9946 AllEltsOk = false;
9947 break;
9948 }
9949 }
9950
9951 if (AllEltsOk) {
9952 // Cast the input vectors to byte vectors.
9953 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9954 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009955 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009956
Chris Lattner0521e3c2008-06-18 04:33:20 +00009957 // Only extract each element once.
9958 Value *ExtractedElts[32];
9959 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9960
Chris Lattnere2ed0572006-04-06 19:19:17 +00009961 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009962 if (isa<UndefValue>(Mask->getOperand(i)))
9963 continue;
9964 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9965 Idx &= 31; // Match the hardware behavior.
9966
9967 if (ExtractedElts[Idx] == 0) {
9968 Instruction *Elt =
Eric Christophera3500da2009-07-25 02:28:41 +00009969 ExtractElementInst::Create(Idx < 16 ? Op0 : Op1,
Owen Anderson1d0be152009-08-13 21:58:54 +00009970 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false), "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009971 InsertNewInstBefore(Elt, CI);
9972 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009973 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009974
Chris Lattner0521e3c2008-06-18 04:33:20 +00009975 // Insert this value into the result vector.
9976 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
Owen Anderson1d0be152009-08-13 21:58:54 +00009977 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009978 "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009979 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009980 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009981 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009982 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009983 }
9984 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009985
Chris Lattner0521e3c2008-06-18 04:33:20 +00009986 case Intrinsic::stackrestore: {
9987 // If the save is right next to the restore, remove the restore. This can
9988 // happen when variable allocas are DCE'd.
9989 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9990 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9991 BasicBlock::iterator BI = SS;
9992 if (&*++BI == II)
9993 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009994 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009995 }
9996
9997 // Scan down this block to see if there is another stack restore in the
9998 // same block without an intervening call/alloca.
9999 BasicBlock::iterator BI = II;
10000 TerminatorInst *TI = II->getParent()->getTerminator();
10001 bool CannotRemove = false;
10002 for (++BI; &*BI != TI; ++BI) {
10003 if (isa<AllocaInst>(BI)) {
10004 CannotRemove = true;
10005 break;
10006 }
Chris Lattneraa0bf522008-06-25 05:59:28 +000010007 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10008 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10009 // If there is a stackrestore below this one, remove this one.
10010 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10011 return EraseInstFromFunction(CI);
10012 // Otherwise, ignore the intrinsic.
10013 } else {
10014 // If we found a non-intrinsic call, we can't remove the stack
10015 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010016 CannotRemove = true;
10017 break;
10018 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010019 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010020 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010021
10022 // If the stack restore is in a return/unwind block and if there are no
10023 // allocas or calls between the restore and the return, nuke the restore.
10024 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10025 return EraseInstFromFunction(CI);
10026 break;
10027 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010028 }
10029
Chris Lattner8b0ea312006-01-13 20:11:04 +000010030 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010031}
10032
10033// InvokeInst simplification
10034//
10035Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010036 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010037}
10038
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010039/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10040/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010041static bool isSafeToEliminateVarargsCast(const CallSite CS,
10042 const CastInst * const CI,
10043 const TargetData * const TD,
10044 const int ix) {
10045 if (!CI->isLosslessCast())
10046 return false;
10047
10048 // The size of ByVal arguments is derived from the type, so we
10049 // can't change to a type with a different size. If the size were
10050 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010051 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010052 return true;
10053
10054 const Type* SrcTy =
10055 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10056 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10057 if (!SrcTy->isSized() || !DstTy->isSized())
10058 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010059 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010060 return false;
10061 return true;
10062}
10063
Chris Lattnera44d8a22003-10-07 22:32:43 +000010064// visitCallSite - Improvements for call and invoke instructions.
10065//
10066Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010067 bool Changed = false;
10068
10069 // If the callee is a constexpr cast of a function, attempt to move the cast
10070 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010071 if (transformConstExprCastCall(CS)) return 0;
10072
Chris Lattner6c266db2003-10-07 22:54:13 +000010073 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010074
Chris Lattner08b22ec2005-05-13 07:09:09 +000010075 if (Function *CalleeF = dyn_cast<Function>(Callee))
10076 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10077 Instruction *OldCall = CS.getInstruction();
10078 // If the call and callee calling conventions don't match, this call must
10079 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010080 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +000010081 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Owen Andersond672ecb2009-07-03 00:17:18 +000010082 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +000010083 if (!OldCall->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010084 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010085 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10086 return EraseInstFromFunction(*OldCall);
10087 return 0;
10088 }
10089
Chris Lattner17be6352004-10-18 02:59:09 +000010090 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10091 // This instruction is not reachable, just remove it. We insert a store to
10092 // undef so that we know that this code is not reachable, despite the fact
10093 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010094 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +000010095 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Chris Lattner17be6352004-10-18 02:59:09 +000010096 CS.getInstruction());
10097
10098 if (!CS.getInstruction()->use_empty())
10099 CS.getInstruction()->
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010100 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010101
10102 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10103 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010104 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010105 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010106 }
Chris Lattner17be6352004-10-18 02:59:09 +000010107 return EraseInstFromFunction(*CS.getInstruction());
10108 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010109
Duncan Sandscdb6d922007-09-17 10:26:40 +000010110 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10111 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10112 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10113 return transformCallThroughTrampoline(CS);
10114
Chris Lattner6c266db2003-10-07 22:54:13 +000010115 const PointerType *PTy = cast<PointerType>(Callee->getType());
10116 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10117 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010118 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010119 // See if we can optimize any arguments passed through the varargs area of
10120 // the call.
10121 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010122 E = CS.arg_end(); I != E; ++I, ++ix) {
10123 CastInst *CI = dyn_cast<CastInst>(*I);
10124 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10125 *I = CI->getOperand(0);
10126 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010127 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010128 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010129 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010130
Duncan Sandsf0c33542007-12-19 21:13:37 +000010131 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010132 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010133 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010134 Changed = true;
10135 }
10136
Chris Lattner6c266db2003-10-07 22:54:13 +000010137 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010138}
10139
Chris Lattner9fe38862003-06-19 17:00:31 +000010140// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10141// attempt to move the cast to the arguments of the call/invoke.
10142//
10143bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10144 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10145 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010146 if (CE->getOpcode() != Instruction::BitCast ||
10147 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010148 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010149 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010150 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010151 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010152
10153 // Okay, this is a cast from a function to a different type. Unless doing so
10154 // would cause a type conversion of one of our arguments, change this call to
10155 // be a direct call with arguments casted to the appropriate types.
10156 //
10157 const FunctionType *FT = Callee->getFunctionType();
10158 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010159 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010160
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010161 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010162 return false; // TODO: Handle multiple return values.
10163
Chris Lattnerf78616b2004-01-14 06:06:08 +000010164 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010165 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010166 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010167 // Conversion is ok if changing from one pointer type to another or from
10168 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010169 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010170 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010171 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010172 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010173 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010174
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010175 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010176 // void -> non-void is handled specially
Owen Anderson1d0be152009-08-13 21:58:54 +000010177 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010178 return false; // Cannot transform this return value.
10179
Chris Lattner58d74912008-03-12 17:45:29 +000010180 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010181 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010182 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010183 return false; // Attribute not compatible with transformed value.
10184 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010185
Chris Lattnerf78616b2004-01-14 06:06:08 +000010186 // If the callsite is an invoke instruction, and the return value is used by
10187 // a PHI node in a successor, we cannot change the return type of the call
10188 // because there is no place to put the cast instruction (without breaking
10189 // the critical edge). Bail out in this case.
10190 if (!Caller->use_empty())
10191 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10192 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10193 UI != E; ++UI)
10194 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10195 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010196 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010197 return false;
10198 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010199
10200 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10201 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010202
Chris Lattner9fe38862003-06-19 17:00:31 +000010203 CallSite::arg_iterator AI = CS.arg_begin();
10204 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10205 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010206 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010207
10208 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010209 return false; // Cannot transform this parameter value.
10210
Devang Patel19c87462008-09-26 22:53:05 +000010211 if (CallerPAL.getParamAttributes(i + 1)
10212 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010213 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010214
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010215 // Converting from one pointer type to another or between a pointer and an
10216 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010217 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010218 (TD && ((isa<PointerType>(ParamTy) ||
10219 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10220 (isa<PointerType>(ActTy) ||
10221 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010222 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010223 }
10224
10225 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010226 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010227 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010228
Chris Lattner58d74912008-03-12 17:45:29 +000010229 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10230 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010231 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010232 // won't be dropping them. Check that these extra arguments have attributes
10233 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010234 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10235 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010236 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010237 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010238 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010239 return false;
10240 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010241
Chris Lattner9fe38862003-06-19 17:00:31 +000010242 // Okay, we decided that this is a safe thing to do: go ahead and start
10243 // inserting cast instructions as necessary...
10244 std::vector<Value*> Args;
10245 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010246 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010247 attrVec.reserve(NumCommonArgs);
10248
10249 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010250 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010251
10252 // If the return value is not being used, the type may not be compatible
10253 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010254 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010255
10256 // Add the new return attributes.
10257 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010258 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010259
10260 AI = CS.arg_begin();
10261 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10262 const Type *ParamTy = FT->getParamType(i);
10263 if ((*AI)->getType() == ParamTy) {
10264 Args.push_back(*AI);
10265 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010266 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010267 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010268 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010269 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010270 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010271
10272 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010273 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010274 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010275 }
10276
10277 // If the function takes more arguments than the call was taking, add them
10278 // now...
10279 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010280 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010281
10282 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010283 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010284 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010285 errs() << "WARNING: While resolving call to function '"
10286 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010287 } else {
10288 // Add all of the arguments in their promoted form to the arg list...
10289 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10290 const Type *PTy = getPromotedType((*AI)->getType());
10291 if (PTy != (*AI)->getType()) {
10292 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010293 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10294 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010295 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010296 InsertNewInstBefore(Cast, *Caller);
10297 Args.push_back(Cast);
10298 } else {
10299 Args.push_back(*AI);
10300 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010301
Duncan Sandse1e520f2008-01-13 08:02:44 +000010302 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010303 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010304 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010305 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010306 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010307 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010308
Devang Patel19c87462008-09-26 22:53:05 +000010309 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10310 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10311
Owen Anderson1d0be152009-08-13 21:58:54 +000010312 if (NewRetTy == Type::getVoidTy(*Context))
Chris Lattner6934a042007-02-11 01:23:03 +000010313 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010314
Eric Christophera66297a2009-07-25 02:45:27 +000010315 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10316 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010317
Chris Lattner9fe38862003-06-19 17:00:31 +000010318 Instruction *NC;
10319 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010320 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010321 Args.begin(), Args.end(),
10322 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010323 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010324 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010325 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010326 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10327 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010328 CallInst *CI = cast<CallInst>(Caller);
10329 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010330 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010331 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010332 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010333 }
10334
Chris Lattner6934a042007-02-11 01:23:03 +000010335 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010336 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010337 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010338 if (NV->getType() != Type::getVoidTy(*Context)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010339 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010340 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010341 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010342
10343 // If this is an invoke instruction, we should insert it after the first
10344 // non-phi, instruction in the normal successor block.
10345 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010346 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010347 InsertNewInstBefore(NC, *I);
10348 } else {
10349 // Otherwise, it's a call, just insert cast right after the call instr
10350 InsertNewInstBefore(NC, *Caller);
10351 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010352 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010353 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010354 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010355 }
10356 }
10357
Owen Anderson1d0be152009-08-13 21:58:54 +000010358 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010359 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010360 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010361 Worklist.Remove(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010362 return true;
10363}
10364
Duncan Sandscdb6d922007-09-17 10:26:40 +000010365// transformCallThroughTrampoline - Turn a call to a function created by the
10366// init_trampoline intrinsic into a direct call to the underlying function.
10367//
10368Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10369 Value *Callee = CS.getCalledValue();
10370 const PointerType *PTy = cast<PointerType>(Callee->getType());
10371 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010372 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010373
10374 // If the call already has the 'nest' attribute somewhere then give up -
10375 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010376 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010377 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010378
10379 IntrinsicInst *Tramp =
10380 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10381
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010382 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010383 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10384 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10385
Devang Patel05988662008-09-25 21:00:45 +000010386 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010387 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010388 unsigned NestIdx = 1;
10389 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010390 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010391
10392 // Look for a parameter marked with the 'nest' attribute.
10393 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10394 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010395 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010396 // Record the parameter type and any other attributes.
10397 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010398 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010399 break;
10400 }
10401
10402 if (NestTy) {
10403 Instruction *Caller = CS.getInstruction();
10404 std::vector<Value*> NewArgs;
10405 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10406
Devang Patel05988662008-09-25 21:00:45 +000010407 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010408 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010409
Duncan Sandscdb6d922007-09-17 10:26:40 +000010410 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010411 // mean appending it. Likewise for attributes.
10412
Devang Patel19c87462008-09-26 22:53:05 +000010413 // Add any result attributes.
10414 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010415 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010416
Duncan Sandscdb6d922007-09-17 10:26:40 +000010417 {
10418 unsigned Idx = 1;
10419 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10420 do {
10421 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010422 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010423 Value *NestVal = Tramp->getOperand(3);
10424 if (NestVal->getType() != NestTy)
10425 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10426 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010427 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010428 }
10429
10430 if (I == E)
10431 break;
10432
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010433 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010434 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010435 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010436 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010437 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010438
10439 ++Idx, ++I;
10440 } while (1);
10441 }
10442
Devang Patel19c87462008-09-26 22:53:05 +000010443 // Add any function attributes.
10444 if (Attributes Attr = Attrs.getFnAttributes())
10445 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10446
Duncan Sandscdb6d922007-09-17 10:26:40 +000010447 // The trampoline may have been bitcast to a bogus type (FTy).
10448 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010449 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010450
Duncan Sandscdb6d922007-09-17 10:26:40 +000010451 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010452 NewTypes.reserve(FTy->getNumParams()+1);
10453
Duncan Sandscdb6d922007-09-17 10:26:40 +000010454 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010455 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010456 {
10457 unsigned Idx = 1;
10458 FunctionType::param_iterator I = FTy->param_begin(),
10459 E = FTy->param_end();
10460
10461 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010462 if (Idx == NestIdx)
10463 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010464 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010465
10466 if (I == E)
10467 break;
10468
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010469 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010470 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010471
10472 ++Idx, ++I;
10473 } while (1);
10474 }
10475
10476 // Replace the trampoline call with a direct call. Let the generic
10477 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010478 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010479 FTy->isVarArg());
10480 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010481 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010482 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010483 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010484 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10485 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010486
10487 Instruction *NewCaller;
10488 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010489 NewCaller = InvokeInst::Create(NewCallee,
10490 II->getNormalDest(), II->getUnwindDest(),
10491 NewArgs.begin(), NewArgs.end(),
10492 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010493 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010494 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010495 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010496 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10497 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010498 if (cast<CallInst>(Caller)->isTailCall())
10499 cast<CallInst>(NewCaller)->setTailCall();
10500 cast<CallInst>(NewCaller)->
10501 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010502 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010503 }
Owen Anderson1d0be152009-08-13 21:58:54 +000010504 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010505 Caller->replaceAllUsesWith(NewCaller);
10506 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010507 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010508 return 0;
10509 }
10510 }
10511
10512 // Replace the trampoline call with a direct call. Since there is no 'nest'
10513 // parameter, there is no need to adjust the argument list. Let the generic
10514 // code sort out any function type mismatches.
10515 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010516 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010517 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010518 CS.setCalledFunction(NewCallee);
10519 return CS.getInstruction();
10520}
10521
Chris Lattner7da52b22006-11-01 04:51:18 +000010522/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10523/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10524/// and a single binop.
10525Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10526 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010527 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010528 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010529 Value *LHSVal = FirstInst->getOperand(0);
10530 Value *RHSVal = FirstInst->getOperand(1);
10531
10532 const Type *LHSType = LHSVal->getType();
10533 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010534
10535 // Scan to see if all operands are the same opcode, all have one use, and all
10536 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010537 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010538 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010539 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010540 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010541 // types or GEP's with different index types.
10542 I->getOperand(0)->getType() != LHSType ||
10543 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010544 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010545
10546 // If they are CmpInst instructions, check their predicates
10547 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10548 if (cast<CmpInst>(I)->getPredicate() !=
10549 cast<CmpInst>(FirstInst)->getPredicate())
10550 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010551
10552 // Keep track of which operand needs a phi node.
10553 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10554 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010555 }
10556
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010557 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010558
Chris Lattner7da52b22006-11-01 04:51:18 +000010559 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010560 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010561 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010562 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010563 NewLHS = PHINode::Create(LHSType,
10564 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010565 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10566 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010567 InsertNewInstBefore(NewLHS, PN);
10568 LHSVal = NewLHS;
10569 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010570
10571 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010572 NewRHS = PHINode::Create(RHSType,
10573 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010574 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10575 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010576 InsertNewInstBefore(NewRHS, PN);
10577 RHSVal = NewRHS;
10578 }
10579
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010580 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010581 if (NewLHS || NewRHS) {
10582 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10583 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10584 if (NewLHS) {
10585 Value *NewInLHS = InInst->getOperand(0);
10586 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10587 }
10588 if (NewRHS) {
10589 Value *NewInRHS = InInst->getOperand(1);
10590 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10591 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010592 }
10593 }
10594
Chris Lattner7da52b22006-11-01 04:51:18 +000010595 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010596 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010597 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010598 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010599 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010600}
10601
Chris Lattner05f18922008-12-01 02:34:36 +000010602Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10603 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10604
10605 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10606 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010607 // This is true if all GEP bases are allocas and if all indices into them are
10608 // constants.
10609 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010610
10611 // Scan to see if all operands are the same opcode, all have one use, and all
10612 // kill their operands (i.e. the operands have one use).
10613 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10614 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10615 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10616 GEP->getNumOperands() != FirstInst->getNumOperands())
10617 return 0;
10618
Chris Lattner36d3e322009-02-21 00:46:50 +000010619 // Keep track of whether or not all GEPs are of alloca pointers.
10620 if (AllBasePointersAreAllocas &&
10621 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10622 !GEP->hasAllConstantIndices()))
10623 AllBasePointersAreAllocas = false;
10624
Chris Lattner05f18922008-12-01 02:34:36 +000010625 // Compare the operand lists.
10626 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10627 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10628 continue;
10629
10630 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10631 // if one of the PHIs has a constant for the index. The index may be
10632 // substantially cheaper to compute for the constants, so making it a
10633 // variable index could pessimize the path. This also handles the case
10634 // for struct indices, which must always be constant.
10635 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10636 isa<ConstantInt>(GEP->getOperand(op)))
10637 return 0;
10638
10639 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10640 return 0;
10641 FixedOperands[op] = 0; // Needs a PHI.
10642 }
10643 }
10644
Chris Lattner36d3e322009-02-21 00:46:50 +000010645 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010646 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010647 // offset calculation, but all the predecessors will have to materialize the
10648 // stack address into a register anyway. We'd actually rather *clone* the
10649 // load up into the predecessors so that we have a load of a gep of an alloca,
10650 // which can usually all be folded into the load.
10651 if (AllBasePointersAreAllocas)
10652 return 0;
10653
Chris Lattner05f18922008-12-01 02:34:36 +000010654 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10655 // that is variable.
10656 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10657
10658 bool HasAnyPHIs = false;
10659 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10660 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10661 Value *FirstOp = FirstInst->getOperand(i);
10662 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10663 FirstOp->getName()+".pn");
10664 InsertNewInstBefore(NewPN, PN);
10665
10666 NewPN->reserveOperandSpace(e);
10667 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10668 OperandPhis[i] = NewPN;
10669 FixedOperands[i] = NewPN;
10670 HasAnyPHIs = true;
10671 }
10672
10673
10674 // Add all operands to the new PHIs.
10675 if (HasAnyPHIs) {
10676 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10677 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10678 BasicBlock *InBB = PN.getIncomingBlock(i);
10679
10680 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10681 if (PHINode *OpPhi = OperandPhis[op])
10682 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10683 }
10684 }
10685
10686 Value *Base = FixedOperands[0];
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010687 GetElementPtrInst *GEP =
10688 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10689 FixedOperands.end());
10690 if (cast<GEPOperator>(FirstInst)->isInBounds())
10691 cast<GEPOperator>(GEP)->setIsInBounds(true);
10692 return GEP;
Chris Lattner05f18922008-12-01 02:34:36 +000010693}
10694
10695
Chris Lattner21550882009-02-23 05:56:17 +000010696/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10697/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010698/// obvious the value of the load is not changed from the point of the load to
10699/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010700///
10701/// Finally, it is safe, but not profitable, to sink a load targetting a
10702/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10703/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010704static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010705 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10706
10707 for (++BBI; BBI != E; ++BBI)
10708 if (BBI->mayWriteToMemory())
10709 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010710
10711 // Check for non-address taken alloca. If not address-taken already, it isn't
10712 // profitable to do this xform.
10713 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10714 bool isAddressTaken = false;
10715 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10716 UI != E; ++UI) {
10717 if (isa<LoadInst>(UI)) continue;
10718 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10719 // If storing TO the alloca, then the address isn't taken.
10720 if (SI->getOperand(1) == AI) continue;
10721 }
10722 isAddressTaken = true;
10723 break;
10724 }
10725
Chris Lattner36d3e322009-02-21 00:46:50 +000010726 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010727 return false;
10728 }
10729
Chris Lattner36d3e322009-02-21 00:46:50 +000010730 // If this load is a load from a GEP with a constant offset from an alloca,
10731 // then we don't want to sink it. In its present form, it will be
10732 // load [constant stack offset]. Sinking it will cause us to have to
10733 // materialize the stack addresses in each predecessor in a register only to
10734 // do a shared load from register in the successor.
10735 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10736 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10737 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10738 return false;
10739
Chris Lattner76c73142006-11-01 07:13:54 +000010740 return true;
10741}
10742
Chris Lattner9fe38862003-06-19 17:00:31 +000010743
Chris Lattnerbac32862004-11-14 19:13:23 +000010744// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10745// operator and they all are only used by the PHI, PHI together their
10746// inputs, and do the operation once, to the result of the PHI.
10747Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10748 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10749
10750 // Scan the instruction, looking for input operations that can be folded away.
10751 // If all input operands to the phi are the same instruction (e.g. a cast from
10752 // the same type or "+42") we can pull the operation through the PHI, reducing
10753 // code size and simplifying code.
10754 Constant *ConstantOp = 0;
10755 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010756 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010757 if (isa<CastInst>(FirstInst)) {
10758 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010759 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010760 // Can fold binop, compare or shift here if the RHS is a constant,
10761 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010762 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010763 if (ConstantOp == 0)
10764 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010765 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10766 isVolatile = LI->isVolatile();
10767 // We can't sink the load if the loaded value could be modified between the
10768 // load and the PHI.
10769 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010770 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010771 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010772
10773 // If the PHI is of volatile loads and the load block has multiple
10774 // successors, sinking it would remove a load of the volatile value from
10775 // the path through the other successor.
10776 if (isVolatile &&
10777 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10778 return 0;
10779
Chris Lattner9c080502006-11-01 07:43:41 +000010780 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010781 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010782 } else {
10783 return 0; // Cannot fold this operation.
10784 }
10785
10786 // Check to see if all arguments are the same operation.
10787 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10788 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10789 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010790 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010791 return 0;
10792 if (CastSrcTy) {
10793 if (I->getOperand(0)->getType() != CastSrcTy)
10794 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010795 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010796 // We can't sink the load if the loaded value could be modified between
10797 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010798 if (LI->isVolatile() != isVolatile ||
10799 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010800 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010801 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010802
Chris Lattner71042962008-07-08 17:18:32 +000010803 // If the PHI is of volatile loads and the load block has multiple
10804 // successors, sinking it would remove a load of the volatile value from
10805 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010806 if (isVolatile &&
10807 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10808 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010809
Chris Lattnerbac32862004-11-14 19:13:23 +000010810 } else if (I->getOperand(1) != ConstantOp) {
10811 return 0;
10812 }
10813 }
10814
10815 // Okay, they are all the same operation. Create a new PHI node of the
10816 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010817 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10818 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010819 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010820
10821 Value *InVal = FirstInst->getOperand(0);
10822 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010823
10824 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010825 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10826 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10827 if (NewInVal != InVal)
10828 InVal = 0;
10829 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10830 }
10831
10832 Value *PhiVal;
10833 if (InVal) {
10834 // The new PHI unions all of the same values together. This is really
10835 // common, so we handle it intelligently here for compile-time speed.
10836 PhiVal = InVal;
10837 delete NewPN;
10838 } else {
10839 InsertNewInstBefore(NewPN, PN);
10840 PhiVal = NewPN;
10841 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010842
Chris Lattnerbac32862004-11-14 19:13:23 +000010843 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010844 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010845 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010846 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010847 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010848 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010849 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010850 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010851 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10852
10853 // If this was a volatile load that we are merging, make sure to loop through
10854 // and mark all the input loads as non-volatile. If we don't do this, we will
10855 // insert a new volatile load and the old ones will not be deletable.
10856 if (isVolatile)
10857 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10858 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10859
10860 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010861}
Chris Lattnera1be5662002-05-02 17:06:02 +000010862
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010863/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10864/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010865static bool DeadPHICycle(PHINode *PN,
10866 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010867 if (PN->use_empty()) return true;
10868 if (!PN->hasOneUse()) return false;
10869
10870 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010871 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010872 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010873
10874 // Don't scan crazily complex things.
10875 if (PotentiallyDeadPHIs.size() == 16)
10876 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010877
10878 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10879 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010880
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010881 return false;
10882}
10883
Chris Lattnercf5008a2007-11-06 21:52:06 +000010884/// PHIsEqualValue - Return true if this phi node is always equal to
10885/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10886/// z = some value; x = phi (y, z); y = phi (x, z)
10887static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10888 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10889 // See if we already saw this PHI node.
10890 if (!ValueEqualPHIs.insert(PN))
10891 return true;
10892
10893 // Don't scan crazily complex things.
10894 if (ValueEqualPHIs.size() == 16)
10895 return false;
10896
10897 // Scan the operands to see if they are either phi nodes or are equal to
10898 // the value.
10899 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10900 Value *Op = PN->getIncomingValue(i);
10901 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10902 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10903 return false;
10904 } else if (Op != NonPhiInVal)
10905 return false;
10906 }
10907
10908 return true;
10909}
10910
10911
Chris Lattner473945d2002-05-06 18:06:38 +000010912// PHINode simplification
10913//
Chris Lattner7e708292002-06-25 16:13:24 +000010914Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010915 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010916 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010917
Owen Anderson7e057142006-07-10 22:03:18 +000010918 if (Value *V = PN.hasConstantValue())
10919 return ReplaceInstUsesWith(PN, V);
10920
Owen Anderson7e057142006-07-10 22:03:18 +000010921 // If all PHI operands are the same operation, pull them through the PHI,
10922 // reducing code size.
10923 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010924 isa<Instruction>(PN.getIncomingValue(1)) &&
10925 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10926 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10927 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10928 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010929 PN.getIncomingValue(0)->hasOneUse())
10930 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10931 return Result;
10932
10933 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10934 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10935 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010936 if (PN.hasOneUse()) {
10937 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10938 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010939 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010940 PotentiallyDeadPHIs.insert(&PN);
10941 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010942 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010943 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010944
10945 // If this phi has a single use, and if that use just computes a value for
10946 // the next iteration of a loop, delete the phi. This occurs with unused
10947 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10948 // common case here is good because the only other things that catch this
10949 // are induction variable analysis (sometimes) and ADCE, which is only run
10950 // late.
10951 if (PHIUser->hasOneUse() &&
10952 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10953 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010954 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010955 }
10956 }
Owen Anderson7e057142006-07-10 22:03:18 +000010957
Chris Lattnercf5008a2007-11-06 21:52:06 +000010958 // We sometimes end up with phi cycles that non-obviously end up being the
10959 // same value, for example:
10960 // z = some value; x = phi (y, z); y = phi (x, z)
10961 // where the phi nodes don't necessarily need to be in the same block. Do a
10962 // quick check to see if the PHI node only contains a single non-phi value, if
10963 // so, scan to see if the phi cycle is actually equal to that value.
10964 {
10965 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10966 // Scan for the first non-phi operand.
10967 while (InValNo != NumOperandVals &&
10968 isa<PHINode>(PN.getIncomingValue(InValNo)))
10969 ++InValNo;
10970
10971 if (InValNo != NumOperandVals) {
10972 Value *NonPhiInVal = PN.getOperand(InValNo);
10973
10974 // Scan the rest of the operands to see if there are any conflicts, if so
10975 // there is no need to recursively scan other phis.
10976 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10977 Value *OpVal = PN.getIncomingValue(InValNo);
10978 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10979 break;
10980 }
10981
10982 // If we scanned over all operands, then we have one unique value plus
10983 // phi values. Scan PHI nodes to see if they all merge in each other or
10984 // the value.
10985 if (InValNo == NumOperandVals) {
10986 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10987 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10988 return ReplaceInstUsesWith(PN, NonPhiInVal);
10989 }
10990 }
10991 }
Chris Lattner60921c92003-12-19 05:58:40 +000010992 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010993}
10994
Chris Lattner7e708292002-06-25 16:13:24 +000010995Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010996 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010997 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010998 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010999 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000011000 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011001
Chris Lattnere87597f2004-10-16 18:11:37 +000011002 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011003 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011004
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011005 bool HasZeroPointerIndex = false;
11006 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11007 HasZeroPointerIndex = C->isNullValue();
11008
11009 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011010 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011011
Chris Lattner28977af2004-04-05 01:30:19 +000011012 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000011013 if (TD) {
11014 bool MadeChange = false;
11015 unsigned PtrSize = TD->getPointerSizeInBits();
11016
11017 gep_type_iterator GTI = gep_type_begin(GEP);
11018 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11019 I != E; ++I, ++GTI) {
11020 if (!isa<SequentialType>(*GTI)) continue;
11021
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011022 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000011023 // to what we need. If narrower, sign-extend it to what we need. This
11024 // explicit cast can make subsequent optimizations more obvious.
11025 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
11026
11027 if (OpBits == PtrSize)
11028 continue;
11029
11030 Instruction::CastOps Opc =
11031 OpBits > PtrSize ? Instruction::Trunc : Instruction::SExt;
11032 *I = InsertCastBefore(Opc, *I, TD->getIntPtrType(GEP.getContext()), GEP);
11033 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000011034 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000011035 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011036 }
Chris Lattner28977af2004-04-05 01:30:19 +000011037
Chris Lattner90ac28c2002-08-02 19:29:35 +000011038 // Combine Indices - If the source pointer to this getelementptr instruction
11039 // is a getelementptr instruction, combine the indices of the two
11040 // getelementptr instructions into a single instruction.
11041 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011042 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000011043 // Note that if our source is a gep chain itself that we wait for that
11044 // chain to be resolved before we perform this transformation. This
11045 // avoids us creating a TON of code in some cases.
11046 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011047 if (GetElementPtrInst *SrcGEP =
11048 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11049 if (SrcGEP->getNumOperands() == 2)
11050 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000011051
Chris Lattner72588fc2007-02-15 22:48:32 +000011052 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011053
11054 // Find out whether the last index in the source GEP is a sequential idx.
11055 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000011056 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11057 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011058 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011059
Chris Lattner90ac28c2002-08-02 19:29:35 +000011060 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011061 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011062 // Replace: gep (gep %P, long B), long A, ...
11063 // With: T = long A+B; gep %P, T, ...
11064 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011065 Value *Sum;
11066 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11067 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000011068 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011069 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000011070 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011071 Sum = SO1;
11072 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000011073 // If they aren't the same type, then the input hasn't been processed
11074 // by the loop above yet (which canonicalizes sequential index types to
11075 // intptr_t). Just avoid transforming this until the input has been
11076 // normalized.
11077 if (SO1->getType() != GO1->getType())
11078 return 0;
Chris Lattner620ce142004-05-07 22:09:22 +000011079 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Chris Lattnerccf4b342009-08-30 04:49:01 +000011080 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
Chris Lattner620ce142004-05-07 22:09:22 +000011081 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011082 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011083 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011084 }
Chris Lattner28977af2004-04-05 01:30:19 +000011085 }
Chris Lattner620ce142004-05-07 22:09:22 +000011086
Chris Lattnerab984842009-08-30 05:30:55 +000011087 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011088 if (Src->getNumOperands() == 2) {
11089 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000011090 GEP.setOperand(1, Sum);
11091 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000011092 }
Chris Lattnerab984842009-08-30 05:30:55 +000011093 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011094 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000011095 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000011096 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011097 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011098 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011099 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000011100 Indices.append(Src->op_begin()+1, Src->op_end());
11101 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011102 }
11103
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011104 if (!Indices.empty()) {
Chris Lattnerccf4b342009-08-30 04:49:01 +000011105 GetElementPtrInst *NewGEP =
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011106 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000011107 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000011108 if (cast<GEPOperator>(&GEP)->isInBounds() && Src->isInBounds())
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011109 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11110 return NewGEP;
11111 }
Chris Lattner6e24d832009-08-30 05:00:50 +000011112 }
11113
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011114 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11115 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011116 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
11117
11118 if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011119 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11120 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011121 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011122 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11123 // into : GEP i8* X, ...
11124 //
Chris Lattnereed48272005-09-13 00:40:14 +000011125 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011126 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11127 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011128 if (const ArrayType *CATy =
11129 dyn_cast<ArrayType>(CPTy->getElementType())) {
11130 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11131 if (CATy->getElementType() == XTy->getElementType()) {
11132 // -> GEP i8* X, ...
11133 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011134 GetElementPtrInst *NewGEP =
11135 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11136 GEP.getName());
11137 if (cast<GEPOperator>(&GEP)->isInBounds())
11138 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11139 return NewGEP;
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011140 } else if (const ArrayType *XATy =
11141 dyn_cast<ArrayType>(XTy->getElementType())) {
11142 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011143 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011144 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011145 // At this point, we know that the cast source type is a pointer
11146 // to an array of the same type as the destination pointer
11147 // array. Because the array type is never stepped over (there
11148 // is a leading zero) we can fold the cast into this GEP.
11149 GEP.setOperand(0, X);
11150 return &GEP;
11151 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011152 }
11153 }
Chris Lattnereed48272005-09-13 00:40:14 +000011154 } else if (GEP.getNumOperands() == 2) {
11155 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011156 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11157 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011158 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11159 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011160 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011161 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11162 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011163 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011164 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011165 Idx[1] = GEP.getOperand(1);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011166 GetElementPtrInst *NewGEP =
11167 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11168 if (cast<GEPOperator>(&GEP)->isInBounds())
11169 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11170 Value *V = InsertNewInstBefore(NewGEP, GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011171 // V and GEP are both pointer types --> BitCast
11172 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011173 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011174
11175 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011176 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011177 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011178 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011179
Owen Anderson1d0be152009-08-13 21:58:54 +000011180 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011181 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011182 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011183
11184 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11185 // allow either a mul, shift, or constant here.
11186 Value *NewIdx = 0;
11187 ConstantInt *Scale = 0;
11188 if (ArrayEltSize == 1) {
11189 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011190 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011191 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011192 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011193 Scale = CI;
11194 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11195 if (Inst->getOpcode() == Instruction::Shl &&
11196 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011197 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11198 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011199 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011200 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011201 NewIdx = Inst->getOperand(0);
11202 } else if (Inst->getOpcode() == Instruction::Mul &&
11203 isa<ConstantInt>(Inst->getOperand(1))) {
11204 Scale = cast<ConstantInt>(Inst->getOperand(1));
11205 NewIdx = Inst->getOperand(0);
11206 }
11207 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011208
Chris Lattner7835cdd2005-09-13 18:36:04 +000011209 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011210 // out, perform the transformation. Note, we don't know whether Scale is
11211 // signed or not. We'll use unsigned version of division/modulo
11212 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011213 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011214 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011215 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011216 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011217 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011218 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11219 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011220 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011221 NewIdx = InsertNewInstBefore(Sc, GEP);
11222 }
11223
11224 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011225 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011226 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011227 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011228 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011229 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011230 if (cast<GEPOperator>(&GEP)->isInBounds())
11231 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
Reid Spencer3da59db2006-11-27 01:05:10 +000011232 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11233 // The NewGEP must be pointer typed, so must the old one -> BitCast
11234 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011235 }
11236 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011237 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011238 }
Chris Lattner58407792009-01-09 04:53:57 +000011239
Chris Lattner46cd5a12009-01-09 05:44:56 +000011240 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011241 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011242 /// Y = gep X, <...constant indices...>
11243 /// into a gep of the original struct. This is important for SROA and alias
11244 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011245 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011246 if (TD &&
11247 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011248 // Determine how much the GEP moves the pointer. We are guaranteed to get
11249 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011250 ConstantInt *OffsetV =
11251 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011252 int64_t Offset = OffsetV->getSExtValue();
11253
11254 // If this GEP instruction doesn't move the pointer, just replace the GEP
11255 // with a bitcast of the real input to the dest type.
11256 if (Offset == 0) {
11257 // If the bitcast is of an allocation, and the allocation will be
11258 // converted to match the type of the cast, don't touch this.
11259 if (isa<AllocationInst>(BCI->getOperand(0))) {
11260 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11261 if (Instruction *I = visitBitCast(*BCI)) {
11262 if (I != BCI) {
11263 I->takeName(BCI);
11264 BCI->getParent()->getInstList().insert(BCI, I);
11265 ReplaceInstUsesWith(*BCI, I);
11266 }
11267 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011268 }
Chris Lattner58407792009-01-09 04:53:57 +000011269 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011270 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011271 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011272
11273 // Otherwise, if the offset is non-zero, we need to find out if there is a
11274 // field at Offset in 'A's type. If so, we can pull the cast through the
11275 // GEP.
11276 SmallVector<Value*, 8> NewIndices;
11277 const Type *InTy =
11278 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011279 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011280 Instruction *NGEP =
11281 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11282 NewIndices.end());
11283 if (NGEP->getType() == GEP.getType()) return NGEP;
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011284 if (cast<GEPOperator>(&GEP)->isInBounds())
11285 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011286 InsertNewInstBefore(NGEP, GEP);
11287 NGEP->takeName(&GEP);
11288 return new BitCastInst(NGEP, GEP.getType());
11289 }
Chris Lattner58407792009-01-09 04:53:57 +000011290 }
11291 }
11292
Chris Lattner8a2a3112001-12-14 16:52:21 +000011293 return 0;
11294}
11295
Chris Lattner0864acf2002-11-04 16:18:53 +000011296Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11297 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011298 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011299 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11300 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011301 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011302 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011303
11304 // Create and insert the replacement instruction...
11305 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +000011306 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011307 else {
11308 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Owen Anderson50dead02009-07-15 23:53:25 +000011309 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011310 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011311
11312 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011313
Chris Lattner0864acf2002-11-04 16:18:53 +000011314 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011315 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011316 //
11317 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011318 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011319
11320 // Now that I is pointing to the first non-allocation-inst in the block,
11321 // insert our getelementptr instruction...
11322 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011323 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011324 Value *Idx[2];
11325 Idx[0] = NullIdx;
11326 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011327 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11328 New->getName()+".sub", It);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011329 cast<GEPOperator>(V)->setIsInBounds(true);
Chris Lattner0864acf2002-11-04 16:18:53 +000011330
11331 // Now make everything use the getelementptr instead of the original
11332 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011333 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011334 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011335 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011336 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011337 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011338
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011339 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011340 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011341 // Note that we only do this for alloca's, because malloc should allocate
11342 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011343 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011344 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011345
11346 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11347 if (AI.getAlignment() == 0)
11348 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11349 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011350
Chris Lattner0864acf2002-11-04 16:18:53 +000011351 return 0;
11352}
11353
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011354Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11355 Value *Op = FI.getOperand(0);
11356
Chris Lattner17be6352004-10-18 02:59:09 +000011357 // free undef -> unreachable.
11358 if (isa<UndefValue>(Op)) {
11359 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011360 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +000011361 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011362 return EraseInstFromFunction(FI);
11363 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011364
Chris Lattner6160e852004-02-28 04:57:37 +000011365 // If we have 'free null' delete the instruction. This can happen in stl code
11366 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011367 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011368 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011369
11370 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11371 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11372 FI.setOperand(0, CI->getOperand(0));
11373 return &FI;
11374 }
11375
11376 // Change free (gep X, 0,0,0,0) into free(X)
11377 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11378 if (GEPI->hasAllZeroIndices()) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000011379 Worklist.Add(GEPI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011380 FI.setOperand(0, GEPI->getOperand(0));
11381 return &FI;
11382 }
11383 }
11384
11385 // Change free(malloc) into nothing, if the malloc has a single use.
11386 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11387 if (MI->hasOneUse()) {
11388 EraseInstFromFunction(FI);
11389 return EraseInstFromFunction(*MI);
11390 }
Chris Lattner6160e852004-02-28 04:57:37 +000011391
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011392 return 0;
11393}
11394
11395
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011396/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011397static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011398 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011399 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011400 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011401 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011402
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011403 if (TD) {
11404 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11405 // Instead of loading constant c string, use corresponding integer value
11406 // directly if string length is small enough.
11407 std::string Str;
11408 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11409 unsigned len = Str.length();
11410 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11411 unsigned numBits = Ty->getPrimitiveSizeInBits();
11412 // Replace LI with immediate integer store.
11413 if ((numBits >> 3) == len + 1) {
11414 APInt StrVal(numBits, 0);
11415 APInt SingleChar(numBits, 0);
11416 if (TD->isLittleEndian()) {
11417 for (signed i = len-1; i >= 0; i--) {
11418 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11419 StrVal = (StrVal << 8) | SingleChar;
11420 }
11421 } else {
11422 for (unsigned i = 0; i < len; i++) {
11423 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11424 StrVal = (StrVal << 8) | SingleChar;
11425 }
11426 // Append NULL at the end.
11427 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011428 StrVal = (StrVal << 8) | SingleChar;
11429 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011430 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011431 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011432 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011433 }
11434 }
11435 }
11436
Mon P Wang6753f952009-02-07 22:19:29 +000011437 const PointerType *DestTy = cast<PointerType>(CI->getType());
11438 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011439 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011440
11441 // If the address spaces don't match, don't eliminate the cast.
11442 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11443 return 0;
11444
Chris Lattnerb89e0712004-07-13 01:49:43 +000011445 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011446
Reid Spencer42230162007-01-22 05:51:25 +000011447 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011448 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011449 // If the source is an array, the code below will not succeed. Check to
11450 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11451 // constants.
11452 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11453 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11454 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011455 Value *Idxs[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011456 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +000011457 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011458 SrcTy = cast<PointerType>(CastOp->getType());
11459 SrcPTy = SrcTy->getElementType();
11460 }
11461
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011462 if (IC.getTargetData() &&
11463 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011464 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011465 // Do not allow turning this into a load of an integer, which is then
11466 // casted to a pointer, this pessimizes pointer analysis a lot.
11467 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011468 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11469 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011470
Chris Lattnerf9527852005-01-31 04:50:46 +000011471 // Okay, we are casting from one integer or pointer type to another of
11472 // the same size. Instead of casting the pointer before the load, cast
11473 // the result of the loaded value.
11474 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11475 CI->getName(),
11476 LI.isVolatile()),LI);
11477 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011478 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011479 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011480 }
11481 }
11482 return 0;
11483}
11484
Chris Lattner833b8a42003-06-26 05:06:25 +000011485Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11486 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011487
Dan Gohman9941f742007-07-20 16:34:21 +000011488 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011489 if (TD) {
11490 unsigned KnownAlign =
11491 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11492 if (KnownAlign >
11493 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11494 LI.getAlignment()))
11495 LI.setAlignment(KnownAlign);
11496 }
Dan Gohman9941f742007-07-20 16:34:21 +000011497
Chris Lattner37366c12005-05-01 04:24:53 +000011498 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011499 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011500 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011501 return Res;
11502
11503 // None of the following transforms are legal for volatile loads.
11504 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011505
Dan Gohman2276a7b2008-10-15 23:19:35 +000011506 // Do really simple store-to-load forwarding and load CSE, to catch cases
11507 // where there are several consequtive memory accesses to the same location,
11508 // separated by a few arithmetic operations.
11509 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011510 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11511 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011512
Christopher Lambb15147e2007-12-29 07:56:53 +000011513 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11514 const Value *GEPI0 = GEPI->getOperand(0);
11515 // TODO: Consider a target hook for valid address spaces for this xform.
11516 if (isa<ConstantPointerNull>(GEPI0) &&
11517 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011518 // Insert a new store to null instruction before the load to indicate
11519 // that this code is not reachable. We do this instead of inserting
11520 // an unreachable instruction directly because we cannot modify the
11521 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011522 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011523 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011524 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011525 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011526 }
Chris Lattner37366c12005-05-01 04:24:53 +000011527
Chris Lattnere87597f2004-10-16 18:11:37 +000011528 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011529 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011530 // TODO: Consider a target hook for valid address spaces for this xform.
11531 if (isa<UndefValue>(C) || (C->isNullValue() &&
11532 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011533 // Insert a new store to null instruction before the load to indicate that
11534 // this code is not reachable. We do this instead of inserting an
11535 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011536 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011537 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011538 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011539 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011540
Chris Lattnere87597f2004-10-16 18:11:37 +000011541 // Instcombine load (constant global) into the value loaded.
11542 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011543 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011544 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011545
Chris Lattnere87597f2004-10-16 18:11:37 +000011546 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011547 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011548 if (CE->getOpcode() == Instruction::GetElementPtr) {
11549 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011550 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011551 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011552 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Andersone922c022009-07-22 00:24:57 +000011553 *Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011554 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011555 if (CE->getOperand(0)->isNullValue()) {
11556 // Insert a new store to null instruction before the load to indicate
11557 // that this code is not reachable. We do this instead of inserting
11558 // an unreachable instruction directly because we cannot modify the
11559 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011560 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011561 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011562 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011563 }
11564
Reid Spencer3da59db2006-11-27 01:05:10 +000011565 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011566 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011567 return Res;
11568 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011569 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011570 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011571
11572 // If this load comes from anywhere in a constant global, and if the global
11573 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011574 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011575 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011576 if (GV->getInitializer()->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +000011577 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011578 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011579 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011580 }
11581 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011582
Chris Lattner37366c12005-05-01 04:24:53 +000011583 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011584 // Change select and PHI nodes to select values instead of addresses: this
11585 // helps alias analysis out a lot, allows many others simplifications, and
11586 // exposes redundancy in the code.
11587 //
11588 // Note that we cannot do the transformation unless we know that the
11589 // introduced loads cannot trap! Something like this is valid as long as
11590 // the condition is always false: load (select bool %C, int* null, int* %G),
11591 // but it would not be valid if we transformed it to load from null
11592 // unconditionally.
11593 //
11594 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11595 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011596 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11597 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011598 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011599 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011600 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011601 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011602 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011603 }
11604
Chris Lattner684fe212004-09-23 15:46:00 +000011605 // load (select (cond, null, P)) -> load P
11606 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11607 if (C->isNullValue()) {
11608 LI.setOperand(0, SI->getOperand(2));
11609 return &LI;
11610 }
11611
11612 // load (select (cond, P, null)) -> load P
11613 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11614 if (C->isNullValue()) {
11615 LI.setOperand(0, SI->getOperand(1));
11616 return &LI;
11617 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011618 }
11619 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011620 return 0;
11621}
11622
Reid Spencer55af2b52007-01-19 21:20:31 +000011623/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011624/// when possible. This makes it generally easy to do alias analysis and/or
11625/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011626static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11627 User *CI = cast<User>(SI.getOperand(1));
11628 Value *CastOp = CI->getOperand(0);
11629
11630 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011631 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11632 if (SrcTy == 0) return 0;
11633
11634 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011635
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011636 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11637 return 0;
11638
Chris Lattner3914f722009-01-24 01:00:13 +000011639 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11640 /// to its first element. This allows us to handle things like:
11641 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11642 /// on 32-bit hosts.
11643 SmallVector<Value*, 4> NewGEPIndices;
11644
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011645 // If the source is an array, the code below will not succeed. Check to
11646 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11647 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011648 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11649 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011650 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011651 NewGEPIndices.push_back(Zero);
11652
11653 while (1) {
11654 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011655 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011656 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011657 NewGEPIndices.push_back(Zero);
11658 SrcPTy = STy->getElementType(0);
11659 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11660 NewGEPIndices.push_back(Zero);
11661 SrcPTy = ATy->getElementType();
11662 } else {
11663 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011664 }
Chris Lattner3914f722009-01-24 01:00:13 +000011665 }
11666
Owen Andersondebcb012009-07-29 22:17:13 +000011667 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011668 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011669
11670 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11671 return 0;
11672
Chris Lattner71759c42009-01-16 20:12:52 +000011673 // If the pointers point into different address spaces or if they point to
11674 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011675 if (!IC.getTargetData() ||
11676 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011677 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011678 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11679 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011680 return 0;
11681
11682 // Okay, we are casting from one integer or pointer type to another of
11683 // the same size. Instead of casting the pointer before
11684 // the store, cast the value to be stored.
11685 Value *NewCast;
11686 Value *SIOp0 = SI.getOperand(0);
11687 Instruction::CastOps opcode = Instruction::BitCast;
11688 const Type* CastSrcTy = SIOp0->getType();
11689 const Type* CastDstTy = SrcPTy;
11690 if (isa<PointerType>(CastDstTy)) {
11691 if (CastSrcTy->isInteger())
11692 opcode = Instruction::IntToPtr;
11693 } else if (isa<IntegerType>(CastDstTy)) {
11694 if (isa<PointerType>(SIOp0->getType()))
11695 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011696 }
Chris Lattner3914f722009-01-24 01:00:13 +000011697
11698 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11699 // emit a GEP to index into its first field.
11700 if (!NewGEPIndices.empty()) {
11701 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Andersonbaf3c402009-07-29 18:55:55 +000011702 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner3914f722009-01-24 01:00:13 +000011703 NewGEPIndices.size());
11704 else
11705 CastOp = IC.InsertNewInstBefore(
11706 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11707 NewGEPIndices.end()), SI);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011708 cast<GEPOperator>(CastOp)->setIsInBounds(true);
Chris Lattner3914f722009-01-24 01:00:13 +000011709 }
11710
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011711 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Andersonbaf3c402009-07-29 18:55:55 +000011712 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011713 else
11714 NewCast = IC.InsertNewInstBefore(
11715 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11716 SI);
11717 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011718}
11719
Chris Lattner4aebaee2008-11-27 08:56:30 +000011720/// equivalentAddressValues - Test if A and B will obviously have the same
11721/// value. This includes recognizing that %t0 and %t1 will have the same
11722/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011723/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011724/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011725/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011726/// %t2 = load i32* %t1
11727///
11728static bool equivalentAddressValues(Value *A, Value *B) {
11729 // Test if the values are trivially equivalent.
11730 if (A == B) return true;
11731
11732 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011733 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11734 // its only used to compare two uses within the same basic block, which
11735 // means that they'll always either have the same value or one of them
11736 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011737 if (isa<BinaryOperator>(A) ||
11738 isa<CastInst>(A) ||
11739 isa<PHINode>(A) ||
11740 isa<GetElementPtrInst>(A))
11741 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011742 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011743 return true;
11744
11745 // Otherwise they may not be equivalent.
11746 return false;
11747}
11748
Dale Johannesen4945c652009-03-03 21:26:39 +000011749// If this instruction has two uses, one of which is a llvm.dbg.declare,
11750// return the llvm.dbg.declare.
11751DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11752 if (!V->hasNUses(2))
11753 return 0;
11754 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11755 UI != E; ++UI) {
11756 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11757 return DI;
11758 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11759 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11760 return DI;
11761 }
11762 }
11763 return 0;
11764}
11765
Chris Lattner2f503e62005-01-31 05:36:43 +000011766Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11767 Value *Val = SI.getOperand(0);
11768 Value *Ptr = SI.getOperand(1);
11769
11770 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011771 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011772 ++NumCombined;
11773 return 0;
11774 }
Chris Lattner836692d2007-01-15 06:51:56 +000011775
11776 // If the RHS is an alloca with a single use, zapify the store, making the
11777 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011778 // If the RHS is an alloca with a two uses, the other one being a
11779 // llvm.dbg.declare, zapify the store and the declare, making the
11780 // alloca dead. We must do this to prevent declare's from affecting
11781 // codegen.
11782 if (!SI.isVolatile()) {
11783 if (Ptr->hasOneUse()) {
11784 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011785 EraseInstFromFunction(SI);
11786 ++NumCombined;
11787 return 0;
11788 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011789 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11790 if (isa<AllocaInst>(GEP->getOperand(0))) {
11791 if (GEP->getOperand(0)->hasOneUse()) {
11792 EraseInstFromFunction(SI);
11793 ++NumCombined;
11794 return 0;
11795 }
11796 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11797 EraseInstFromFunction(*DI);
11798 EraseInstFromFunction(SI);
11799 ++NumCombined;
11800 return 0;
11801 }
11802 }
11803 }
11804 }
11805 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11806 EraseInstFromFunction(*DI);
11807 EraseInstFromFunction(SI);
11808 ++NumCombined;
11809 return 0;
11810 }
Chris Lattner836692d2007-01-15 06:51:56 +000011811 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011812
Dan Gohman9941f742007-07-20 16:34:21 +000011813 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011814 if (TD) {
11815 unsigned KnownAlign =
11816 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11817 if (KnownAlign >
11818 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11819 SI.getAlignment()))
11820 SI.setAlignment(KnownAlign);
11821 }
Dan Gohman9941f742007-07-20 16:34:21 +000011822
Dale Johannesenacb51a32009-03-03 01:43:03 +000011823 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011824 // stores to the same location, separated by a few arithmetic operations. This
11825 // situation often occurs with bitfield accesses.
11826 BasicBlock::iterator BBI = &SI;
11827 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11828 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011829 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011830 // Don't count debug info directives, lest they affect codegen,
11831 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11832 // It is necessary for correctness to skip those that feed into a
11833 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011834 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011835 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011836 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011837 continue;
11838 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011839
11840 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11841 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011842 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11843 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011844 ++NumDeadStore;
11845 ++BBI;
11846 EraseInstFromFunction(*PrevSI);
11847 continue;
11848 }
11849 break;
11850 }
11851
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011852 // If this is a load, we have to stop. However, if the loaded value is from
11853 // the pointer we're loading and is producing the pointer we're storing,
11854 // then *this* store is dead (X = load P; store X -> P).
11855 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011856 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11857 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011858 EraseInstFromFunction(SI);
11859 ++NumCombined;
11860 return 0;
11861 }
11862 // Otherwise, this is a load from some other location. Stores before it
11863 // may not be dead.
11864 break;
11865 }
11866
Chris Lattner9ca96412006-02-08 03:25:32 +000011867 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011868 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011869 break;
11870 }
11871
11872
11873 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011874
11875 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011876 if (isa<ConstantPointerNull>(Ptr) &&
11877 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011878 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011879 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011880 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000011881 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011882 ++NumCombined;
11883 }
11884 return 0; // Do not modify these!
11885 }
11886
11887 // store undef, Ptr -> noop
11888 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011889 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011890 ++NumCombined;
11891 return 0;
11892 }
11893
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011894 // If the pointer destination is a cast, see if we can fold the cast into the
11895 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011896 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011897 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11898 return Res;
11899 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011900 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011901 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11902 return Res;
11903
Chris Lattner408902b2005-09-12 23:23:25 +000011904
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011905 // If this store is the last instruction in the basic block (possibly
11906 // excepting debug info instructions and the pointer bitcasts that feed
11907 // into them), and if the block ends with an unconditional branch, try
11908 // to move it to the successor block.
11909 BBI = &SI;
11910 do {
11911 ++BBI;
11912 } while (isa<DbgInfoIntrinsic>(BBI) ||
11913 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011914 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011915 if (BI->isUnconditional())
11916 if (SimplifyStoreAtEndOfBlock(SI))
11917 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011918
Chris Lattner2f503e62005-01-31 05:36:43 +000011919 return 0;
11920}
11921
Chris Lattner3284d1f2007-04-15 00:07:55 +000011922/// SimplifyStoreAtEndOfBlock - Turn things like:
11923/// if () { *P = v1; } else { *P = v2 }
11924/// into a phi node with a store in the successor.
11925///
Chris Lattner31755a02007-04-15 01:02:18 +000011926/// Simplify things like:
11927/// *P = v1; if () { *P = v2; }
11928/// into a phi node with a store in the successor.
11929///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011930bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11931 BasicBlock *StoreBB = SI.getParent();
11932
11933 // Check to see if the successor block has exactly two incoming edges. If
11934 // so, see if the other predecessor contains a store to the same location.
11935 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011936 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011937
11938 // Determine whether Dest has exactly two predecessors and, if so, compute
11939 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011940 pred_iterator PI = pred_begin(DestBB);
11941 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011942 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011943 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011944 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011945 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011946 return false;
11947
11948 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011949 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011950 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011951 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011952 }
Chris Lattner31755a02007-04-15 01:02:18 +000011953 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011954 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011955
11956 // Bail out if all the relevant blocks aren't distinct (this can happen,
11957 // for example, if SI is in an infinite loop)
11958 if (StoreBB == DestBB || OtherBB == DestBB)
11959 return false;
11960
Chris Lattner31755a02007-04-15 01:02:18 +000011961 // Verify that the other block ends in a branch and is not otherwise empty.
11962 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011963 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011964 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011965 return false;
11966
Chris Lattner31755a02007-04-15 01:02:18 +000011967 // If the other block ends in an unconditional branch, check for the 'if then
11968 // else' case. there is an instruction before the branch.
11969 StoreInst *OtherStore = 0;
11970 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011971 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011972 // Skip over debugging info.
11973 while (isa<DbgInfoIntrinsic>(BBI) ||
11974 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11975 if (BBI==OtherBB->begin())
11976 return false;
11977 --BBI;
11978 }
11979 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011980 OtherStore = dyn_cast<StoreInst>(BBI);
11981 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11982 return false;
11983 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011984 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011985 // destinations is StoreBB, then we have the if/then case.
11986 if (OtherBr->getSuccessor(0) != StoreBB &&
11987 OtherBr->getSuccessor(1) != StoreBB)
11988 return false;
11989
11990 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011991 // if/then triangle. See if there is a store to the same ptr as SI that
11992 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011993 for (;; --BBI) {
11994 // Check to see if we find the matching store.
11995 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11996 if (OtherStore->getOperand(1) != SI.getOperand(1))
11997 return false;
11998 break;
11999 }
Eli Friedman6903a242008-06-13 22:02:12 +000012000 // If we find something that may be using or overwriting the stored
12001 // value, or if we run out of instructions, we can't do the xform.
12002 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012003 BBI == OtherBB->begin())
12004 return false;
12005 }
12006
12007 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012008 // make sure nothing reads or overwrites the stored value in
12009 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012010 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12011 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012012 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012013 return false;
12014 }
12015 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012016
Chris Lattner31755a02007-04-15 01:02:18 +000012017 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012018 Value *MergedVal = OtherStore->getOperand(0);
12019 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012020 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012021 PN->reserveOperandSpace(2);
12022 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012023 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12024 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012025 }
12026
12027 // Advance to a place where it is safe to insert the new store and
12028 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012029 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012030 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12031 OtherStore->isVolatile()), *BBI);
12032
12033 // Nuke the old stores.
12034 EraseInstFromFunction(SI);
12035 EraseInstFromFunction(*OtherStore);
12036 ++NumCombined;
12037 return true;
12038}
12039
Chris Lattner2f503e62005-01-31 05:36:43 +000012040
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012041Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12042 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012043 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012044 BasicBlock *TrueDest;
12045 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000012046 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012047 !isa<Constant>(X)) {
12048 // Swap Destinations and condition...
12049 BI.setCondition(X);
12050 BI.setSuccessor(0, FalseDest);
12051 BI.setSuccessor(1, TrueDest);
12052 return &BI;
12053 }
12054
Reid Spencere4d87aa2006-12-23 06:05:41 +000012055 // Cannonicalize fcmp_one -> fcmp_oeq
12056 FCmpInst::Predicate FPred; Value *Y;
12057 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012058 TrueDest, FalseDest)) &&
12059 BI.getCondition()->hasOneUse())
12060 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12061 FPred == FCmpInst::FCMP_OGE) {
12062 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12063 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12064
12065 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000012066 BI.setSuccessor(0, FalseDest);
12067 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012068 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012069 return &BI;
12070 }
12071
12072 // Cannonicalize icmp_ne -> icmp_eq
12073 ICmpInst::Predicate IPred;
12074 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012075 TrueDest, FalseDest)) &&
12076 BI.getCondition()->hasOneUse())
12077 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12078 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12079 IPred == ICmpInst::ICMP_SGE) {
12080 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12081 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12082 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000012083 BI.setSuccessor(0, FalseDest);
12084 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012085 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000012086 return &BI;
12087 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012088
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012089 return 0;
12090}
Chris Lattner0864acf2002-11-04 16:18:53 +000012091
Chris Lattner46238a62004-07-03 00:26:11 +000012092Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12093 Value *Cond = SI.getCondition();
12094 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12095 if (I->getOpcode() == Instruction::Add)
12096 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12097 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12098 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012099 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012100 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012101 AddRHS));
12102 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000012103 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012104 return &SI;
12105 }
12106 }
12107 return 0;
12108}
12109
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012110Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012111 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012112
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012113 if (!EV.hasIndices())
12114 return ReplaceInstUsesWith(EV, Agg);
12115
12116 if (Constant *C = dyn_cast<Constant>(Agg)) {
12117 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012118 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012119
12120 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012121 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012122
12123 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12124 // Extract the element indexed by the first index out of the constant
12125 Value *V = C->getOperand(*EV.idx_begin());
12126 if (EV.getNumIndices() > 1)
12127 // Extract the remaining indices out of the constant indexed by the
12128 // first index
12129 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12130 else
12131 return ReplaceInstUsesWith(EV, V);
12132 }
12133 return 0; // Can't handle other constants
12134 }
12135 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12136 // We're extracting from an insertvalue instruction, compare the indices
12137 const unsigned *exti, *exte, *insi, *inse;
12138 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12139 exte = EV.idx_end(), inse = IV->idx_end();
12140 exti != exte && insi != inse;
12141 ++exti, ++insi) {
12142 if (*insi != *exti)
12143 // The insert and extract both reference distinctly different elements.
12144 // This means the extract is not influenced by the insert, and we can
12145 // replace the aggregate operand of the extract with the aggregate
12146 // operand of the insert. i.e., replace
12147 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12148 // %E = extractvalue { i32, { i32 } } %I, 0
12149 // with
12150 // %E = extractvalue { i32, { i32 } } %A, 0
12151 return ExtractValueInst::Create(IV->getAggregateOperand(),
12152 EV.idx_begin(), EV.idx_end());
12153 }
12154 if (exti == exte && insi == inse)
12155 // Both iterators are at the end: Index lists are identical. Replace
12156 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12157 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12158 // with "i32 42"
12159 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12160 if (exti == exte) {
12161 // The extract list is a prefix of the insert list. i.e. replace
12162 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12163 // %E = extractvalue { i32, { i32 } } %I, 1
12164 // with
12165 // %X = extractvalue { i32, { i32 } } %A, 1
12166 // %E = insertvalue { i32 } %X, i32 42, 0
12167 // by switching the order of the insert and extract (though the
12168 // insertvalue should be left in, since it may have other uses).
12169 Value *NewEV = InsertNewInstBefore(
12170 ExtractValueInst::Create(IV->getAggregateOperand(),
12171 EV.idx_begin(), EV.idx_end()),
12172 EV);
12173 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12174 insi, inse);
12175 }
12176 if (insi == inse)
12177 // The insert list is a prefix of the extract list
12178 // We can simply remove the common indices from the extract and make it
12179 // operate on the inserted value instead of the insertvalue result.
12180 // i.e., replace
12181 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12182 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12183 // with
12184 // %E extractvalue { i32 } { i32 42 }, 0
12185 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12186 exti, exte);
12187 }
12188 // Can't simplify extracts from other values. Note that nested extracts are
12189 // already simplified implicitely by the above (extract ( extract (insert) )
12190 // will be translated into extract ( insert ( extract ) ) first and then just
12191 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012192 return 0;
12193}
12194
Chris Lattner220b0cf2006-03-05 00:22:33 +000012195/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12196/// is to leave as a vector operation.
12197static bool CheapToScalarize(Value *V, bool isConstant) {
12198 if (isa<ConstantAggregateZero>(V))
12199 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012200 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012201 if (isConstant) return true;
12202 // If all elts are the same, we can extract.
12203 Constant *Op0 = C->getOperand(0);
12204 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12205 if (C->getOperand(i) != Op0)
12206 return false;
12207 return true;
12208 }
12209 Instruction *I = dyn_cast<Instruction>(V);
12210 if (!I) return false;
12211
12212 // Insert element gets simplified to the inserted element or is deleted if
12213 // this is constant idx extract element and its a constant idx insertelt.
12214 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12215 isa<ConstantInt>(I->getOperand(2)))
12216 return true;
12217 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12218 return true;
12219 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12220 if (BO->hasOneUse() &&
12221 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12222 CheapToScalarize(BO->getOperand(1), isConstant)))
12223 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012224 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12225 if (CI->hasOneUse() &&
12226 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12227 CheapToScalarize(CI->getOperand(1), isConstant)))
12228 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012229
12230 return false;
12231}
12232
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012233/// Read and decode a shufflevector mask.
12234///
12235/// It turns undef elements into values that are larger than the number of
12236/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012237static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12238 unsigned NElts = SVI->getType()->getNumElements();
12239 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12240 return std::vector<unsigned>(NElts, 0);
12241 if (isa<UndefValue>(SVI->getOperand(2)))
12242 return std::vector<unsigned>(NElts, 2*NElts);
12243
12244 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012245 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012246 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12247 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012248 Result.push_back(NElts*2); // undef -> 8
12249 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012250 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012251 return Result;
12252}
12253
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012254/// FindScalarElement - Given a vector and an element number, see if the scalar
12255/// value is already around as a register, for example if it were inserted then
12256/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012257static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012258 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012259 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12260 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012261 unsigned Width = PTy->getNumElements();
12262 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012263 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012264
12265 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012266 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012267 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012268 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012269 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012270 return CP->getOperand(EltNo);
12271 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12272 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012273 if (!isa<ConstantInt>(III->getOperand(2)))
12274 return 0;
12275 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012276
12277 // If this is an insert to the element we are looking for, return the
12278 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012279 if (EltNo == IIElt)
12280 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012281
12282 // Otherwise, the insertelement doesn't modify the value, recurse on its
12283 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012284 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012285 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012286 unsigned LHSWidth =
12287 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012288 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012289 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012290 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012291 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012292 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012293 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012294 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012295 }
12296
12297 // Otherwise, we don't know.
12298 return 0;
12299}
12300
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012301Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012302 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012303 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012304 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012305
Dan Gohman07a96762007-07-16 14:29:03 +000012306 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012307 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012308 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012309
Reid Spencer9d6565a2007-02-15 02:26:10 +000012310 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012311 // If vector val is constant with all elements the same, replace EI with
12312 // that element. When the elements are not identical, we cannot replace yet
12313 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012314 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012315 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012316 if (C->getOperand(i) != op0) {
12317 op0 = 0;
12318 break;
12319 }
12320 if (op0)
12321 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012322 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012323
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012324 // If extracting a specified index from the vector, see if we can recursively
12325 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012326 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012327 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedman76e7ba82009-07-18 19:04:16 +000012328 unsigned VectorWidth =
12329 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012330
12331 // If this is extracting an invalid index, turn this into undef, to avoid
12332 // crashing the code below.
12333 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012334 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012335
Chris Lattner867b99f2006-10-05 06:55:50 +000012336 // This instruction only demands the single element from the input vector.
12337 // If the input vector has a single use, simplify it based on this use
12338 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012339 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012340 APInt UndefElts(VectorWidth, 0);
12341 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012342 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012343 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012344 EI.setOperand(0, V);
12345 return &EI;
12346 }
12347 }
12348
Owen Andersond672ecb2009-07-03 00:17:18 +000012349 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012350 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012351
12352 // If the this extractelement is directly using a bitcast from a vector of
12353 // the same number of elements, see if we can find the source element from
12354 // it. In this case, we will end up needing to bitcast the scalars.
12355 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12356 if (const VectorType *VT =
12357 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12358 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012359 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12360 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012361 return new BitCastInst(Elt, EI.getType());
12362 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012363 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012364
Chris Lattner73fa49d2006-05-25 22:53:38 +000012365 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012366 if (I->hasOneUse()) {
12367 // Push extractelement into predecessor operation if legal and
12368 // profitable to do so
12369 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012370 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12371 if (CheapToScalarize(BO, isConstantElt)) {
12372 ExtractElementInst *newEI0 =
Eric Christophera3500da2009-07-25 02:28:41 +000012373 ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
Chris Lattner220b0cf2006-03-05 00:22:33 +000012374 EI.getName()+".lhs");
12375 ExtractElementInst *newEI1 =
Eric Christophera3500da2009-07-25 02:28:41 +000012376 ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
Chris Lattner220b0cf2006-03-05 00:22:33 +000012377 EI.getName()+".rhs");
12378 InsertNewInstBefore(newEI0, EI);
12379 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012380 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012381 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012382 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012383 unsigned AS =
12384 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012385 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Mon P Wang7c4efa62009-08-13 05:12:13 +000012386 PointerType::get(EI.getType(), AS),*I);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012387 GetElementPtrInst *GEP =
12388 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmand6aa02d2009-07-28 01:40:03 +000012389 cast<GEPOperator>(GEP)->setIsInBounds(true);
Mon P Wang7c4efa62009-08-13 05:12:13 +000012390 InsertNewInstBefore(GEP, *I);
12391 LoadInst* Load = new LoadInst(GEP, "tmp");
12392 InsertNewInstBefore(Load, *I);
12393 return ReplaceInstUsesWith(EI, Load);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012394 }
12395 }
12396 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12397 // Extracting the inserted element?
12398 if (IE->getOperand(2) == EI.getOperand(1))
12399 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12400 // If the inserted and extracted elements are constants, they must not
12401 // be the same value, extract from the pre-inserted value instead.
12402 if (isa<Constant>(IE->getOperand(2)) &&
12403 isa<Constant>(EI.getOperand(1))) {
Chris Lattnerc3a3e362009-08-30 06:20:05 +000012404 AddOperandsToWorkList(EI);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012405 EI.setOperand(0, IE->getOperand(0));
12406 return &EI;
12407 }
12408 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12409 // If this is extracting an element from a shufflevector, figure out where
12410 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012411 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12412 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012413 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012414 unsigned LHSWidth =
12415 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12416
12417 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012418 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012419 else if (SrcIdx < LHSWidth*2) {
12420 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012421 Src = SVI->getOperand(1);
12422 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012423 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012424 }
Eric Christophera3500da2009-07-25 02:28:41 +000012425 return ExtractElementInst::Create(Src,
Owen Anderson1d0be152009-08-13 21:58:54 +000012426 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012427 }
12428 }
Eli Friedman2451a642009-07-18 23:06:53 +000012429 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012430 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012431 return 0;
12432}
12433
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012434/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12435/// elements from either LHS or RHS, return the shuffle mask and true.
12436/// Otherwise, return false.
12437static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012438 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012439 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012440 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12441 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012442 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012443
12444 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012445 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012446 return true;
12447 } else if (V == LHS) {
12448 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012449 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012450 return true;
12451 } else if (V == RHS) {
12452 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012453 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012454 return true;
12455 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12456 // If this is an insert of an extract from some other vector, include it.
12457 Value *VecOp = IEI->getOperand(0);
12458 Value *ScalarOp = IEI->getOperand(1);
12459 Value *IdxOp = IEI->getOperand(2);
12460
Chris Lattnerd929f062006-04-27 21:14:21 +000012461 if (!isa<ConstantInt>(IdxOp))
12462 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012463 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012464
12465 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12466 // Okay, we can handle this if the vector we are insertinting into is
12467 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012468 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012469 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012470 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012471 return true;
12472 }
12473 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12474 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012475 EI->getOperand(0)->getType() == V->getType()) {
12476 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012477 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012478
12479 // This must be extracting from either LHS or RHS.
12480 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12481 // Okay, we can handle this if the vector we are insertinting into is
12482 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012483 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012484 // If so, update the mask to reflect the inserted value.
12485 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012486 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012487 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012488 } else {
12489 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012490 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012491 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012492
12493 }
12494 return true;
12495 }
12496 }
12497 }
12498 }
12499 }
12500 // TODO: Handle shufflevector here!
12501
12502 return false;
12503}
12504
12505/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12506/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12507/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012508static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012509 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012510 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012511 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012512 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012513 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012514
12515 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012516 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012517 return V;
12518 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012519 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012520 return V;
12521 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12522 // If this is an insert of an extract from some other vector, include it.
12523 Value *VecOp = IEI->getOperand(0);
12524 Value *ScalarOp = IEI->getOperand(1);
12525 Value *IdxOp = IEI->getOperand(2);
12526
12527 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12528 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12529 EI->getOperand(0)->getType() == V->getType()) {
12530 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012531 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12532 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012533
12534 // Either the extracted from or inserted into vector must be RHSVec,
12535 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012536 if (EI->getOperand(0) == RHS || RHS == 0) {
12537 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012538 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012539 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012540 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012541 return V;
12542 }
12543
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012544 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012545 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12546 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012547 // Everything but the extracted element is replaced with the RHS.
12548 for (unsigned i = 0; i != NumElts; ++i) {
12549 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012550 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012551 }
12552 return V;
12553 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012554
12555 // If this insertelement is a chain that comes from exactly these two
12556 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012557 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12558 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012559 return EI->getOperand(0);
12560
Chris Lattnerefb47352006-04-15 01:39:45 +000012561 }
12562 }
12563 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012564 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012565
12566 // Otherwise, can't do anything fancy. Return an identity vector.
12567 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012568 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012569 return V;
12570}
12571
12572Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12573 Value *VecOp = IE.getOperand(0);
12574 Value *ScalarOp = IE.getOperand(1);
12575 Value *IdxOp = IE.getOperand(2);
12576
Chris Lattner599ded12007-04-09 01:11:16 +000012577 // Inserting an undef or into an undefined place, remove this.
12578 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12579 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012580
Chris Lattnerefb47352006-04-15 01:39:45 +000012581 // If the inserted element was extracted from some other vector, and if the
12582 // indexes are constant, try to turn this into a shufflevector operation.
12583 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12584 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12585 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012586 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012587 unsigned ExtractedIdx =
12588 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012589 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012590
12591 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12592 return ReplaceInstUsesWith(IE, VecOp);
12593
12594 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012595 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012596
12597 // If we are extracting a value from a vector, then inserting it right
12598 // back into the same place, just use the input vector.
12599 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12600 return ReplaceInstUsesWith(IE, VecOp);
12601
12602 // We could theoretically do this for ANY input. However, doing so could
12603 // turn chains of insertelement instructions into a chain of shufflevector
12604 // instructions, and right now we do not merge shufflevectors. As such,
12605 // only do this in a situation where it is clear that there is benefit.
12606 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12607 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12608 // the values of VecOp, except then one read from EIOp0.
12609 // Build a new shuffle mask.
12610 std::vector<Constant*> Mask;
12611 if (isa<UndefValue>(VecOp))
Owen Anderson1d0be152009-08-13 21:58:54 +000012612 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012613 else {
12614 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Anderson1d0be152009-08-13 21:58:54 +000012615 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
Chris Lattnerefb47352006-04-15 01:39:45 +000012616 NumVectorElts));
12617 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012618 Mask[InsertedIdx] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012619 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012620 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012621 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012622 }
12623
12624 // If this insertelement isn't used by some other insertelement, turn it
12625 // (and any insertelements it points to), into one big shuffle.
12626 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12627 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012628 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012629 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012630 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012631 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012632 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012633 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012634 }
12635 }
12636 }
12637
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012638 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12639 APInt UndefElts(VWidth, 0);
12640 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12641 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12642 return &IE;
12643
Chris Lattnerefb47352006-04-15 01:39:45 +000012644 return 0;
12645}
12646
12647
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012648Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12649 Value *LHS = SVI.getOperand(0);
12650 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012651 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012652
12653 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012654
Chris Lattner867b99f2006-10-05 06:55:50 +000012655 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012656 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012657 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012658
Dan Gohman488fbfc2008-09-09 18:11:14 +000012659 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012660
12661 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12662 return 0;
12663
Evan Cheng388df622009-02-03 10:05:09 +000012664 APInt UndefElts(VWidth, 0);
12665 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12666 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012667 LHS = SVI.getOperand(0);
12668 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012669 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012670 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012671
Chris Lattner863bcff2006-05-25 23:48:38 +000012672 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12673 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12674 if (LHS == RHS || isa<UndefValue>(LHS)) {
12675 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012676 // shuffle(undef,undef,mask) -> undef.
12677 return ReplaceInstUsesWith(SVI, LHS);
12678 }
12679
Chris Lattner863bcff2006-05-25 23:48:38 +000012680 // Remap any references to RHS to use LHS.
12681 std::vector<Constant*> Elts;
12682 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012683 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012684 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012685 else {
12686 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012687 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012688 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012689 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012690 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012691 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012692 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012693 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012694 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012695 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012696 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012697 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012698 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012699 LHS = SVI.getOperand(0);
12700 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012701 MadeChange = true;
12702 }
12703
Chris Lattner7b2e27922006-05-26 00:29:06 +000012704 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012705 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012706
Chris Lattner863bcff2006-05-25 23:48:38 +000012707 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12708 if (Mask[i] >= e*2) continue; // Ignore undef values.
12709 // Is this an identity shuffle of the LHS value?
12710 isLHSID &= (Mask[i] == i);
12711
12712 // Is this an identity shuffle of the RHS value?
12713 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012714 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012715
Chris Lattner863bcff2006-05-25 23:48:38 +000012716 // Eliminate identity shuffles.
12717 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12718 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012719
Chris Lattner7b2e27922006-05-26 00:29:06 +000012720 // If the LHS is a shufflevector itself, see if we can combine it with this
12721 // one without producing an unusual shuffle. Here we are really conservative:
12722 // we are absolutely afraid of producing a shuffle mask not in the input
12723 // program, because the code gen may not be smart enough to turn a merged
12724 // shuffle into two specific shuffles: it may produce worse code. As such,
12725 // we only merge two shuffles if the result is one of the two input shuffle
12726 // masks. In this case, merging the shuffles just removes one instruction,
12727 // which we know is safe. This is good for things like turning:
12728 // (splat(splat)) -> splat.
12729 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12730 if (isa<UndefValue>(RHS)) {
12731 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12732
12733 std::vector<unsigned> NewMask;
12734 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12735 if (Mask[i] >= 2*e)
12736 NewMask.push_back(2*e);
12737 else
12738 NewMask.push_back(LHSMask[Mask[i]]);
12739
12740 // If the result mask is equal to the src shuffle or this shuffle mask, do
12741 // the replacement.
12742 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012743 unsigned LHSInNElts =
12744 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012745 std::vector<Constant*> Elts;
12746 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012747 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012748 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012749 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012750 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012751 }
12752 }
12753 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12754 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012755 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012756 }
12757 }
12758 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012759
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012760 return MadeChange ? &SVI : 0;
12761}
12762
12763
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012764
Chris Lattnerea1c4542004-12-08 23:43:58 +000012765
12766/// TryToSinkInstruction - Try to move the specified instruction from its
12767/// current block into the beginning of DestBlock, which can only happen if it's
12768/// safe to move the instruction past all of the instructions between it and the
12769/// end of its block.
12770static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12771 assert(I->hasOneUse() && "Invariants didn't hold!");
12772
Chris Lattner108e9022005-10-27 17:13:11 +000012773 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012774 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012775 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012776
Chris Lattnerea1c4542004-12-08 23:43:58 +000012777 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012778 if (isa<AllocaInst>(I) && I->getParent() ==
12779 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012780 return false;
12781
Chris Lattner96a52a62004-12-09 07:14:34 +000012782 // We can only sink load instructions if there is nothing between the load and
12783 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012784 if (I->mayReadFromMemory()) {
12785 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012786 Scan != E; ++Scan)
12787 if (Scan->mayWriteToMemory())
12788 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012789 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012790
Dan Gohman02dea8b2008-05-23 21:05:58 +000012791 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012792
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012793 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012794 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012795 ++NumSunkInst;
12796 return true;
12797}
12798
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012799
12800/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12801/// all reachable code to the worklist.
12802///
12803/// This has a couple of tricks to make the code faster and more powerful. In
12804/// particular, we constant fold and DCE instructions as we go, to avoid adding
12805/// them to the worklist (this significantly speeds up instcombine on code where
12806/// many instructions are dead or constant). Additionally, if we find a branch
12807/// whose condition is a known constant, we only visit the reachable successors.
12808///
12809static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012810 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012811 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012812 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012813 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012814 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012815
Chris Lattner2c7718a2007-03-23 19:17:18 +000012816 while (!Worklist.empty()) {
12817 BB = Worklist.back();
12818 Worklist.pop_back();
12819
12820 // We have now visited this block! If we've already been here, ignore it.
12821 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012822
12823 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012824 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12825 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012826
Chris Lattner2c7718a2007-03-23 19:17:18 +000012827 // DCE instruction if trivially dead.
12828 if (isInstructionTriviallyDead(Inst)) {
12829 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012830 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012831 Inst->eraseFromParent();
12832 continue;
12833 }
12834
12835 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012836 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012837 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12838 << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012839 Inst->replaceAllUsesWith(C);
12840 ++NumConstProp;
12841 Inst->eraseFromParent();
12842 continue;
12843 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012844
Devang Patel7fe1dec2008-11-19 18:56:50 +000012845 // If there are two consecutive llvm.dbg.stoppoint calls then
12846 // it is likely that the optimizer deleted code in between these
12847 // two intrinsics.
12848 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12849 if (DBI_Next) {
12850 if (DBI_Prev
12851 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12852 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012853 IC.Worklist.Remove(DBI_Prev);
Devang Patel7fe1dec2008-11-19 18:56:50 +000012854 DBI_Prev->eraseFromParent();
12855 }
12856 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012857 } else {
12858 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012859 }
12860
Chris Lattner7a1e9242009-08-30 06:13:40 +000012861 IC.Worklist.Add(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012862 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012863
12864 // Recursively visit successors. If this is a branch or switch on a
12865 // constant, only visit the reachable successor.
12866 TerminatorInst *TI = BB->getTerminator();
12867 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12868 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12869 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012870 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012871 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012872 continue;
12873 }
12874 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12875 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12876 // See if this is an explicit destination.
12877 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12878 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012879 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012880 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012881 continue;
12882 }
12883
12884 // Otherwise it is the default destination.
12885 Worklist.push_back(SI->getSuccessor(0));
12886 continue;
12887 }
12888 }
12889
12890 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12891 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012892 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012893}
12894
Chris Lattnerec9c3582007-03-03 02:04:50 +000012895bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012896 bool Changed = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012897 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012898
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012899 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12900 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012901
Chris Lattnerb3d59702005-07-07 20:40:38 +000012902 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012903 // Do a depth-first traversal of the function, populate the worklist with
12904 // the reachable instructions. Ignore blocks that are not reachable. Keep
12905 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012906 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012907 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012908
Chris Lattnerb3d59702005-07-07 20:40:38 +000012909 // Do a quick scan over the function. If we find any blocks that are
12910 // unreachable, remove any instructions inside of them. This prevents
12911 // the instcombine code from having to deal with some bad special cases.
12912 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12913 if (!Visited.count(BB)) {
12914 Instruction *Term = BB->getTerminator();
12915 while (Term != BB->begin()) { // Remove instrs bottom-up
12916 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012917
Chris Lattnerbdff5482009-08-23 04:37:46 +000012918 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012919 // A debug intrinsic shouldn't force another iteration if we weren't
12920 // going to do one without it.
12921 if (!isa<DbgInfoIntrinsic>(I)) {
12922 ++NumDeadInst;
12923 Changed = true;
12924 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012925 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012926 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012927 I->eraseFromParent();
12928 }
12929 }
12930 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012931
Chris Lattner873ff012009-08-30 05:55:36 +000012932 while (!Worklist.isEmpty()) {
12933 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012934 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012935
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012936 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012937 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012938 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000012939 EraseInstFromFunction(*I);
12940 ++NumDeadInst;
Chris Lattner1e19d602009-01-31 07:04:22 +000012941 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012942 continue;
12943 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012944
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012945 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012946 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012947 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012948
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012949 // Add operands to the worklist.
Chris Lattnerc736d562002-12-05 22:41:53 +000012950 ReplaceInstUsesWith(*I, C);
Chris Lattner62b14df2002-09-02 04:59:56 +000012951 ++NumConstProp;
Chris Lattner7a1e9242009-08-30 06:13:40 +000012952 EraseInstFromFunction(*I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012953 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012954 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012955 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012956
Eli Friedmanfd2934f2009-07-15 22:13:34 +000012957 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012958 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012959 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12960 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000012961 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12962 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012963 if (NewC != CE) {
12964 i->set(NewC);
12965 Changed = true;
12966 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012967 }
12968
Chris Lattnerea1c4542004-12-08 23:43:58 +000012969 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012970 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012971 BasicBlock *BB = I->getParent();
12972 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12973 if (UserParent != BB) {
12974 bool UserIsSuccessor = false;
12975 // See if the user is one of our successors.
12976 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12977 if (*SI == UserParent) {
12978 UserIsSuccessor = true;
12979 break;
12980 }
12981
12982 // If the user is one of our immediate successors, and if that successor
12983 // only has us as a predecessors (we'd have to split the critical edge
12984 // otherwise), we can keep going.
12985 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12986 next(pred_begin(UserParent)) == pred_end(UserParent))
12987 // Okay, the CFG is simple enough, try to sink this instruction.
12988 Changed |= TryToSinkInstruction(I, UserParent);
12989 }
12990 }
12991
Chris Lattner8a2a3112001-12-14 16:52:21 +000012992 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000012993#ifndef NDEBUG
12994 std::string OrigI;
12995#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000012996 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000012997 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012998 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012999 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013000 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013001 DEBUG(errs() << "IC: Old = " << *I << '\n'
13002 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000013003
Chris Lattnerf523d062004-06-09 05:08:07 +000013004 // Everything uses the new instruction now.
13005 I->replaceAllUsesWith(Result);
13006
13007 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000013008 Worklist.Add(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000013009 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013010
Chris Lattner6934a042007-02-11 01:23:03 +000013011 // Move the name to the new instruction first.
13012 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013013
13014 // Insert the new instruction into the basic block...
13015 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013016 BasicBlock::iterator InsertPos = I;
13017
13018 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13019 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13020 ++InsertPos;
13021
13022 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013023
Chris Lattner7a1e9242009-08-30 06:13:40 +000013024 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000013025 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013026#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000013027 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13028 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000013029#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013030
Chris Lattner90ac28c2002-08-02 19:29:35 +000013031 // If the instruction was modified, it's possible that it is now dead.
13032 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013033 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013034 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000013035 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013036 Worklist.Add(I);
Chris Lattnerec9c3582007-03-03 02:04:50 +000013037 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013038 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013039 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013040 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013041 }
13042 }
13043
Chris Lattner873ff012009-08-30 05:55:36 +000013044 Worklist.Zap();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013045 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013046}
13047
Chris Lattnerec9c3582007-03-03 02:04:50 +000013048
13049bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013050 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013051 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000013052
Chris Lattnerec9c3582007-03-03 02:04:50 +000013053 bool EverMadeChange = false;
13054
13055 // Iterate while there is work to do.
13056 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013057 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013058 EverMadeChange = true;
13059 return EverMadeChange;
13060}
13061
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013062FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013063 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013064}