blob: 81423b740b6973c9cbd69a1a1509b5eeb86a2722 [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"
Victor Hernandez83d63912009-09-18 22:35:49 +000045#include "llvm/Analysis/MallocHelper.h"
Chris Lattner173234a2008-06-02 01:18:21 +000046#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000047#include "llvm/Target/TargetData.h"
48#include "llvm/Transforms/Utils/BasicBlockUtils.h"
49#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000050#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000051#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000052#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000053#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000054#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000055#include "llvm/Support/InstVisitor.h"
Chris Lattner74381062009-08-30 07:44:24 +000056#include "llvm/Support/IRBuilder.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000057#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000058#include "llvm/Support/PatternMatch.h"
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000059#include "llvm/Support/TargetFolder.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000060#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000061#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000062#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000063#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000064#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000065#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000066#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000067#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000068using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000069using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000070
Chris Lattner0e5f4992006-12-19 21:40:18 +000071STATISTIC(NumCombined , "Number of insts combined");
72STATISTIC(NumConstProp, "Number of constant folds");
73STATISTIC(NumDeadInst , "Number of dead inst eliminated");
74STATISTIC(NumDeadStore, "Number of dead stores eliminated");
75STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000076
Chris Lattner0e5f4992006-12-19 21:40:18 +000077namespace {
Chris Lattner873ff012009-08-30 05:55:36 +000078 /// InstCombineWorklist - This is the worklist management logic for
79 /// InstCombine.
80 class InstCombineWorklist {
81 SmallVector<Instruction*, 256> Worklist;
82 DenseMap<Instruction*, unsigned> WorklistMap;
83
84 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
85 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
86 public:
87 InstCombineWorklist() {}
88
89 bool isEmpty() const { return Worklist.empty(); }
90
91 /// Add - Add the specified instruction to the worklist if it isn't already
92 /// in it.
93 void Add(Instruction *I) {
Jeffrey Yasskin43069632009-10-08 00:12:24 +000094 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
95 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner873ff012009-08-30 05:55:36 +000096 Worklist.push_back(I);
Jeffrey Yasskin43069632009-10-08 00:12:24 +000097 }
Chris Lattner873ff012009-08-30 05:55:36 +000098 }
99
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000100 void AddValue(Value *V) {
101 if (Instruction *I = dyn_cast<Instruction>(V))
102 Add(I);
103 }
104
Chris Lattner67f7d542009-10-12 03:58:40 +0000105 /// AddInitialGroup - Add the specified batch of stuff in reverse order.
106 /// which should only be done when the worklist is empty and when the group
107 /// has no duplicates.
108 void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
109 assert(Worklist.empty() && "Worklist must be empty to add initial group");
110 Worklist.reserve(NumEntries+16);
111 DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
112 for (; NumEntries; --NumEntries) {
113 Instruction *I = List[NumEntries-1];
114 WorklistMap.insert(std::make_pair(I, Worklist.size()));
115 Worklist.push_back(I);
116 }
117 }
118
Chris Lattner7a1e9242009-08-30 06:13:40 +0000119 // Remove - remove I from the worklist if it exists.
Chris Lattner873ff012009-08-30 05:55:36 +0000120 void Remove(Instruction *I) {
121 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
122 if (It == WorklistMap.end()) return; // Not in worklist.
123
124 // Don't bother moving everything down, just null out the slot.
125 Worklist[It->second] = 0;
126
127 WorklistMap.erase(It);
128 }
129
130 Instruction *RemoveOne() {
131 Instruction *I = Worklist.back();
132 Worklist.pop_back();
133 WorklistMap.erase(I);
134 return I;
135 }
136
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000137 /// AddUsersToWorkList - When an instruction is simplified, add all users of
138 /// the instruction to the work lists because they might get more simplified
139 /// now.
140 ///
141 void AddUsersToWorkList(Instruction &I) {
142 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
143 UI != UE; ++UI)
144 Add(cast<Instruction>(*UI));
145 }
146
Chris Lattner873ff012009-08-30 05:55:36 +0000147
148 /// Zap - check that the worklist is empty and nuke the backing store for
149 /// the map if it is large.
150 void Zap() {
151 assert(WorklistMap.empty() && "Worklist empty, but map not?");
152
153 // Do an explicit clear, this shrinks the map if needed.
154 WorklistMap.clear();
155 }
156 };
157} // end anonymous namespace.
158
159
160namespace {
Chris Lattner74381062009-08-30 07:44:24 +0000161 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
162 /// just like the normal insertion helper, but also adds any new instructions
163 /// to the instcombine worklist.
164 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
165 InstCombineWorklist &Worklist;
166 public:
167 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
168
169 void InsertHelper(Instruction *I, const Twine &Name,
170 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
171 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
172 Worklist.Add(I);
173 }
174 };
175} // end anonymous namespace
176
177
178namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000179 class InstCombiner : public FunctionPass,
180 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000181 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +0000182 bool MustPreserveLCSSA;
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000183 bool MadeIRChange;
Chris Lattnerdbab3862007-03-02 21:28:56 +0000184 public:
Chris Lattner75551f72009-08-30 17:53:59 +0000185 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000186 InstCombineWorklist Worklist;
187
Chris Lattner74381062009-08-30 07:44:24 +0000188 /// Builder - This is an IRBuilder that automatically inserts new
189 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +0000190 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000191 BuilderTy *Builder;
Chris Lattner74381062009-08-30 07:44:24 +0000192
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000193 static char ID; // Pass identification, replacement for typeid
Chris Lattner74381062009-08-30 07:44:24 +0000194 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Devang Patel794fd752007-05-01 21:15:47 +0000195
Owen Andersone922c022009-07-22 00:24:57 +0000196 LLVMContext *Context;
197 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +0000198
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000199 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000200 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000201
202 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000203
Chris Lattner97e52e42002-04-28 21:27:06 +0000204 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000205 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000206 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000207 }
208
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000209 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000210
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000211 // Visitation implementation - Implement instruction combining for different
212 // instruction types. The semantics are as follows:
213 // Return Value:
214 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000215 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000216 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000217 //
Chris Lattner7e708292002-06-25 16:13:24 +0000218 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000219 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000220 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000221 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000222 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000223 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000224 Instruction *visitURem(BinaryOperator &I);
225 Instruction *visitSRem(BinaryOperator &I);
226 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000227 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000228 Instruction *commonRemTransforms(BinaryOperator &I);
229 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000230 Instruction *commonDivTransforms(BinaryOperator &I);
231 Instruction *commonIDivTransforms(BinaryOperator &I);
232 Instruction *visitUDiv(BinaryOperator &I);
233 Instruction *visitSDiv(BinaryOperator &I);
234 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000235 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000236 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000237 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000238 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000239 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000240 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000241 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000242 Instruction *visitOr (BinaryOperator &I);
243 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000244 Instruction *visitShl(BinaryOperator &I);
245 Instruction *visitAShr(BinaryOperator &I);
246 Instruction *visitLShr(BinaryOperator &I);
247 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000248 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
249 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000250 Instruction *visitFCmpInst(FCmpInst &I);
251 Instruction *visitICmpInst(ICmpInst &I);
252 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000253 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
254 Instruction *LHS,
255 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000256 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
257 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000258
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000259 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000260 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000261 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000262 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000263 Instruction *commonCastTransforms(CastInst &CI);
264 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000265 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000266 Instruction *visitTrunc(TruncInst &CI);
267 Instruction *visitZExt(ZExtInst &CI);
268 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000269 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000270 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000271 Instruction *visitFPToUI(FPToUIInst &FI);
272 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000273 Instruction *visitUIToFP(CastInst &CI);
274 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000275 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000276 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000277 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000278 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
279 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000280 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000281 Instruction *visitSelectInst(SelectInst &SI);
282 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000283 Instruction *visitCallInst(CallInst &CI);
284 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000285 Instruction *visitPHINode(PHINode &PN);
286 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000287 Instruction *visitAllocaInst(AllocaInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000288 Instruction *visitFreeInst(FreeInst &FI);
Victor Hernandez66284e02009-10-24 04:23:03 +0000289 Instruction *visitFree(Instruction &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000290 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000291 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000292 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000293 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000294 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000295 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000296 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000297 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000298
299 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000300 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000301
Chris Lattner9fe38862003-06-19 17:00:31 +0000302 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000303 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000304 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000305 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000306 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
307 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000308 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000309 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
310
Chris Lattner9fe38862003-06-19 17:00:31 +0000311
Chris Lattner28977af2004-04-05 01:30:19 +0000312 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000313 // InsertNewInstBefore - insert an instruction New before instruction Old
314 // in the program. Add the new instruction to the worklist.
315 //
Chris Lattner955f3312004-09-28 21:48:02 +0000316 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000317 assert(New && New->getParent() == 0 &&
318 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000319 BasicBlock *BB = Old.getParent();
320 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000321 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000322 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000323 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000324
Chris Lattner8b170942002-08-09 23:47:40 +0000325 // ReplaceInstUsesWith - This method is to be used when an instruction is
326 // found to be dead, replacable with another preexisting expression. Here
327 // we add all uses of I to the worklist, replace all uses of I with the new
328 // value, then return I, so that the inst combiner will know that I was
329 // modified.
330 //
331 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000332 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000333
334 // If we are replacing the instruction with itself, this must be in a
335 // segment of unreachable code, so just clobber the instruction.
336 if (&I == V)
337 V = UndefValue::get(I.getType());
338
339 I.replaceAllUsesWith(V);
340 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000341 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000342
343 // EraseInstFromFunction - When dealing with an instruction that has side
344 // effects or produces a void value, we can't rely on DCE to delete the
345 // instruction. Instead, visit methods should return the value returned by
346 // this function.
347 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000348 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner931f8f32009-08-31 05:17:58 +0000349
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000350 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000351 // Make sure that we reprocess all operands now that we reduced their
352 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000353 if (I.getNumOperands() < 8) {
354 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
355 if (Instruction *Op = dyn_cast<Instruction>(*i))
356 Worklist.Add(Op);
357 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000358 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000359 I.eraseFromParent();
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000360 MadeIRChange = true;
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000361 return 0; // Don't do anything with FI
362 }
Chris Lattner173234a2008-06-02 01:18:21 +0000363
364 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
365 APInt &KnownOne, unsigned Depth = 0) const {
366 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
367 }
368
369 bool MaskedValueIsZero(Value *V, const APInt &Mask,
370 unsigned Depth = 0) const {
371 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
372 }
373 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
374 return llvm::ComputeNumSignBits(Op, TD, Depth);
375 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000376
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000377 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000378
Reid Spencere4d87aa2006-12-23 06:05:41 +0000379 /// SimplifyCommutative - This performs a few simplifications for
380 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000381 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000382
Reid Spencere4d87aa2006-12-23 06:05:41 +0000383 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
384 /// most-complex to least-complex order.
385 bool SimplifyCompare(CmpInst &I);
386
Chris Lattner886ab6c2009-01-31 08:15:18 +0000387 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
388 /// based on the demanded bits.
389 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
390 APInt& KnownZero, APInt& KnownOne,
391 unsigned Depth);
392 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000393 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000394 unsigned Depth=0);
395
396 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
397 /// SimplifyDemandedBits knows about. See if the instruction has any
398 /// properties that allow us to simplify its operands.
399 bool SimplifyDemandedInstructionBits(Instruction &Inst);
400
Evan Cheng388df622009-02-03 10:05:09 +0000401 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
402 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000403
Chris Lattner5d1704d2009-09-27 19:57:57 +0000404 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
405 // which has a PHI node as operand #0, see if we can fold the instruction
406 // into the PHI (which is only possible if all operands to the PHI are
407 // constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000408 //
409 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
410 // that would normally be unprofitable because they strongly encourage jump
411 // threading.
412 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Chris Lattner4e998b22004-09-29 05:07:12 +0000413
Chris Lattnerbac32862004-11-14 19:13:23 +0000414 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
415 // operator and they all are only used by the PHI, PHI together their
416 // inputs, and do the operation once, to the result of the PHI.
417 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000418 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000419 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
420
Chris Lattner7da52b22006-11-01 04:51:18 +0000421
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000422 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
423 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000424
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000425 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000426 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000427 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000428 bool isSigned, bool Inside, Instruction &IB);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000429 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000430 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000431 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000432 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000433 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000434
Chris Lattnerafe91a52006-06-15 19:07:26 +0000435
Reid Spencerc55b2432006-12-13 18:21:21 +0000436 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000437
Dan Gohman6de29f82009-06-15 22:12:54 +0000438 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000439 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000440 unsigned GetOrEnforceKnownAlignment(Value *V,
441 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000442
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000443 };
Chris Lattner873ff012009-08-30 05:55:36 +0000444} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000445
Dan Gohman844731a2008-05-13 00:00:25 +0000446char InstCombiner::ID = 0;
447static RegisterPass<InstCombiner>
448X("instcombine", "Combine redundant instructions");
449
Chris Lattner4f98c562003-03-10 21:43:22 +0000450// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000451// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000452static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000453 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000454 if (BinaryOperator::isNeg(V) ||
455 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000456 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000457 return 3;
458 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000459 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000460 if (isa<Argument>(V)) return 3;
461 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000462}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000463
Chris Lattnerc8802d22003-03-11 00:12:48 +0000464// isOnlyUse - Return true if this instruction will be deleted if we stop using
465// it.
466static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000467 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000468}
469
Chris Lattner4cb170c2004-02-23 06:38:22 +0000470// getPromotedType - Return the specified type promoted as it would be to pass
471// though a va_arg area...
472static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000473 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
474 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000475 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000476 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000477 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000478}
479
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000480/// getBitCastOperand - If the specified operand is a CastInst, a constant
481/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
482/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000483static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000484 if (Operator *O = dyn_cast<Operator>(V)) {
485 if (O->getOpcode() == Instruction::BitCast)
486 return O->getOperand(0);
487 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
488 if (GEP->hasAllZeroIndices())
489 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000490 }
Chris Lattnereed48272005-09-13 00:40:14 +0000491 return 0;
492}
493
Reid Spencer3da59db2006-11-27 01:05:10 +0000494/// This function is a wrapper around CastInst::isEliminableCastPair. It
495/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000496static Instruction::CastOps
497isEliminableCastPair(
498 const CastInst *CI, ///< The first cast instruction
499 unsigned opcode, ///< The opcode of the second cast instruction
500 const Type *DstTy, ///< The target type for the second cast instruction
501 TargetData *TD ///< The target data for pointer size
502) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000503
Reid Spencer3da59db2006-11-27 01:05:10 +0000504 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
505 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000506
Reid Spencer3da59db2006-11-27 01:05:10 +0000507 // Get the opcodes of the two Cast instructions
508 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
509 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000510
Chris Lattnera0e69692009-03-24 18:35:40 +0000511 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000512 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000513 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000514
515 // We don't want to form an inttoptr or ptrtoint that converts to an integer
516 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000517 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000518 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000519 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000520 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000521 Res = 0;
522
523 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000524}
525
526/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
527/// in any code being generated. It does not require codegen if V is simple
528/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000529static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
530 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000531 if (V->getType() == Ty || isa<Constant>(V)) return false;
532
Chris Lattner01575b72006-05-25 23:24:33 +0000533 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000534 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000535 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000536 return false;
537 return true;
538}
539
Chris Lattner4f98c562003-03-10 21:43:22 +0000540// SimplifyCommutative - This performs a few simplifications for commutative
541// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000542//
Chris Lattner4f98c562003-03-10 21:43:22 +0000543// 1. Order operands such that they are listed from right (least complex) to
544// left (most complex). This puts constants before unary operators before
545// binary operators.
546//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000547// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
548// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000549//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000550bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000551 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000552 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000553 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000554
Chris Lattner4f98c562003-03-10 21:43:22 +0000555 if (!I.isAssociative()) return Changed;
556 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000557 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
558 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
559 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000560 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000561 cast<Constant>(I.getOperand(1)),
562 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000563 I.setOperand(0, Op->getOperand(0));
564 I.setOperand(1, Folded);
565 return true;
566 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
567 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
568 isOnlyUse(Op) && isOnlyUse(Op1)) {
569 Constant *C1 = cast<Constant>(Op->getOperand(1));
570 Constant *C2 = cast<Constant>(Op1->getOperand(1));
571
572 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000573 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000574 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000575 Op1->getOperand(0),
576 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000577 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000578 I.setOperand(0, New);
579 I.setOperand(1, Folded);
580 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000581 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000582 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000583 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000584}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000585
Reid Spencere4d87aa2006-12-23 06:05:41 +0000586/// SimplifyCompare - For a CmpInst this function just orders the operands
587/// so that theyare listed from right (least complex) to left (most complex).
588/// This puts constants before unary operators before binary operators.
589bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman14ef4f02009-08-29 23:39:38 +0000590 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000591 return false;
592 I.swapOperands();
593 // Compare instructions are not associative so there's nothing else we can do.
594 return true;
595}
596
Chris Lattner8d969642003-03-10 23:06:50 +0000597// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
598// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000599//
Dan Gohman186a6362009-08-12 16:04:34 +0000600static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000601 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000602 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000603
Chris Lattner0ce85802004-12-14 20:08:06 +0000604 // Constants can be considered to be negated values if they can be folded.
605 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000606 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000607
608 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
609 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000610 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000611
Chris Lattner8d969642003-03-10 23:06:50 +0000612 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000613}
614
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000615// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
616// instruction if the LHS is a constant negative zero (which is the 'negate'
617// form).
618//
Dan Gohman186a6362009-08-12 16:04:34 +0000619static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000620 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000621 return BinaryOperator::getFNegArgument(V);
622
623 // Constants can be considered to be negated values if they can be folded.
624 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000625 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000626
627 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
628 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000629 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000630
631 return 0;
632}
633
Chris Lattner863928f2009-10-26 01:06:31 +0000634static inline Value *dyn_castNotVal(Value *V) {
Evan Cheng85def162009-10-26 03:51:32 +0000635 if (BinaryOperator::isNot(V))
636 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000637
638 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000639 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000640 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000641 return 0;
642}
643
Chris Lattnerc8802d22003-03-11 00:12:48 +0000644// dyn_castFoldableMul - If this value is a multiply that can be folded into
645// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000646// non-constant operand of the multiply, and set CST to point to the multiplier.
647// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000648//
Dan Gohman186a6362009-08-12 16:04:34 +0000649static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000650 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000651 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000652 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000653 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000654 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000655 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000656 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000657 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000658 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000659 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000660 CST = ConstantInt::get(V->getType()->getContext(),
661 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000662 return I->getOperand(0);
663 }
664 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000665 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000666}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000667
Reid Spencer7177c3a2007-03-25 05:33:51 +0000668/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000669static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000670 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000671 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000672}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000673/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000674static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000675 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000676 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000677}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000678/// MultiplyOverflows - True if the multiply can not be expressed in an int
679/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000680static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000681 uint32_t W = C1->getBitWidth();
682 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
683 if (sign) {
684 LHSExt.sext(W * 2);
685 RHSExt.sext(W * 2);
686 } else {
687 LHSExt.zext(W * 2);
688 RHSExt.zext(W * 2);
689 }
690
691 APInt MulExt = LHSExt * RHSExt;
692
693 if (sign) {
694 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
695 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
696 return MulExt.slt(Min) || MulExt.sgt(Max);
697 } else
698 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
699}
Chris Lattner955f3312004-09-28 21:48:02 +0000700
Reid Spencere7816b52007-03-08 01:52:58 +0000701
Chris Lattner255d8912006-02-11 09:31:47 +0000702/// ShrinkDemandedConstant - Check to see if the specified operand of the
703/// specified instruction is a constant integer. If so, check to see if there
704/// are any bits set in the constant that are not demanded. If so, shrink the
705/// constant and return true.
706static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000707 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000708 assert(I && "No instruction?");
709 assert(OpNo < I->getNumOperands() && "Operand index too large");
710
711 // If the operand is not a constant integer, nothing to do.
712 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
713 if (!OpC) return false;
714
715 // If there are no bits set that aren't demanded, nothing to do.
716 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
717 if ((~Demanded & OpC->getValue()) == 0)
718 return false;
719
720 // This instruction is producing bits that are not demanded. Shrink the RHS.
721 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000722 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000723 return true;
724}
725
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000726// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
727// set of known zero and one bits, compute the maximum and minimum values that
728// could have the specified known zero and known one bits, returning them in
729// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000730static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000731 const APInt& KnownOne,
732 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000733 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
734 KnownZero.getBitWidth() == Min.getBitWidth() &&
735 KnownZero.getBitWidth() == Max.getBitWidth() &&
736 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000737 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000738
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000739 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
740 // bit if it is unknown.
741 Min = KnownOne;
742 Max = KnownOne|UnknownBits;
743
Dan Gohman1c8491e2009-04-25 17:12:48 +0000744 if (UnknownBits.isNegative()) { // Sign bit is unknown
745 Min.set(Min.getBitWidth()-1);
746 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000747 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000748}
749
750// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
751// a set of known zero and one bits, compute the maximum and minimum values that
752// could have the specified known zero and known one bits, returning them in
753// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000754static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000755 const APInt &KnownOne,
756 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000757 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
758 KnownZero.getBitWidth() == Min.getBitWidth() &&
759 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000760 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000761 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000762
763 // The minimum value is when the unknown bits are all zeros.
764 Min = KnownOne;
765 // The maximum value is when the unknown bits are all ones.
766 Max = KnownOne|UnknownBits;
767}
Chris Lattner255d8912006-02-11 09:31:47 +0000768
Chris Lattner886ab6c2009-01-31 08:15:18 +0000769/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
770/// SimplifyDemandedBits knows about. See if the instruction has any
771/// properties that allow us to simplify its operands.
772bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000773 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000774 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
775 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
776
777 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
778 KnownZero, KnownOne, 0);
779 if (V == 0) return false;
780 if (V == &Inst) return true;
781 ReplaceInstUsesWith(Inst, V);
782 return true;
783}
784
785/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
786/// specified instruction operand if possible, updating it in place. It returns
787/// true if it made any change and false otherwise.
788bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
789 APInt &KnownZero, APInt &KnownOne,
790 unsigned Depth) {
791 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
792 KnownZero, KnownOne, Depth);
793 if (NewVal == 0) return false;
Dan Gohmane41a1152009-10-05 16:31:55 +0000794 U = NewVal;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000795 return true;
796}
797
798
799/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
800/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000801/// that only the bits set in DemandedMask of the result of V are ever used
802/// downstream. Consequently, depending on the mask and V, it may be possible
803/// to replace V with a constant or one of its operands. In such cases, this
804/// function does the replacement and returns true. In all other cases, it
805/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000806/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000807/// to be zero in the expression. These are provided to potentially allow the
808/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
809/// the expression. KnownOne and KnownZero always follow the invariant that
810/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
811/// the bits in KnownOne and KnownZero may only be accurate for those bits set
812/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
813/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000814///
815/// This returns null if it did not change anything and it permits no
816/// simplification. This returns V itself if it did some simplification of V's
817/// operands based on the information about what bits are demanded. This returns
818/// some other non-null value if it found out that V is equal to another value
819/// in the context where the specified bits are demanded, but not for all users.
820Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
821 APInt &KnownZero, APInt &KnownOne,
822 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000823 assert(V != 0 && "Null pointer of Value???");
824 assert(Depth <= 6 && "Limit Search Depth");
825 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000826 const Type *VTy = V->getType();
827 assert((TD || !isa<PointerType>(VTy)) &&
828 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000829 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
830 (!VTy->isIntOrIntVector() ||
831 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000832 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000833 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000834 "Value *V, DemandedMask, KnownZero and KnownOne "
835 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000836 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
837 // We know all of the bits for a constant!
838 KnownOne = CI->getValue() & DemandedMask;
839 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000840 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000841 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000842 if (isa<ConstantPointerNull>(V)) {
843 // We know all of the bits for a constant!
844 KnownOne.clear();
845 KnownZero = DemandedMask;
846 return 0;
847 }
848
Chris Lattner08d2cc72009-01-31 07:26:06 +0000849 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000850 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000851 if (DemandedMask == 0) { // Not demanding any bits from V.
852 if (isa<UndefValue>(V))
853 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000854 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000855 }
856
Chris Lattner4598c942009-01-31 08:24:16 +0000857 if (Depth == 6) // Limit search depth.
858 return 0;
859
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000860 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
861 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
862
Dan Gohman1c8491e2009-04-25 17:12:48 +0000863 Instruction *I = dyn_cast<Instruction>(V);
864 if (!I) {
865 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
866 return 0; // Only analyze instructions.
867 }
868
Chris Lattner4598c942009-01-31 08:24:16 +0000869 // If there are multiple uses of this value and we aren't at the root, then
870 // we can't do any simplifications of the operands, because DemandedMask
871 // only reflects the bits demanded by *one* of the users.
872 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000873 // Despite the fact that we can't simplify this instruction in all User's
874 // context, we can at least compute the knownzero/knownone bits, and we can
875 // do simplifications that apply to *just* the one user if we know that
876 // this instruction has a simpler value in that context.
877 if (I->getOpcode() == Instruction::And) {
878 // If either the LHS or the RHS are Zero, the result is zero.
879 ComputeMaskedBits(I->getOperand(1), DemandedMask,
880 RHSKnownZero, RHSKnownOne, Depth+1);
881 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
882 LHSKnownZero, LHSKnownOne, Depth+1);
883
884 // If all of the demanded bits are known 1 on one side, return the other.
885 // These bits cannot contribute to the result of the 'and' in this
886 // context.
887 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
888 (DemandedMask & ~LHSKnownZero))
889 return I->getOperand(0);
890 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
891 (DemandedMask & ~RHSKnownZero))
892 return I->getOperand(1);
893
894 // If all of the demanded bits in the inputs are known zeros, return zero.
895 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000896 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000897
898 } else if (I->getOpcode() == Instruction::Or) {
899 // We can simplify (X|Y) -> X or Y in the user's context if we know that
900 // only bits from X or Y are demanded.
901
902 // If either the LHS or the RHS are One, the result is One.
903 ComputeMaskedBits(I->getOperand(1), DemandedMask,
904 RHSKnownZero, RHSKnownOne, Depth+1);
905 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
906 LHSKnownZero, LHSKnownOne, Depth+1);
907
908 // If all of the demanded bits are known zero on one side, return the
909 // other. These bits cannot contribute to the result of the 'or' in this
910 // context.
911 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
912 (DemandedMask & ~LHSKnownOne))
913 return I->getOperand(0);
914 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
915 (DemandedMask & ~RHSKnownOne))
916 return I->getOperand(1);
917
918 // If all of the potentially set bits on one side are known to be set on
919 // the other side, just use the 'other' side.
920 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
921 (DemandedMask & (~RHSKnownZero)))
922 return I->getOperand(0);
923 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
924 (DemandedMask & (~LHSKnownZero)))
925 return I->getOperand(1);
926 }
927
Chris Lattner4598c942009-01-31 08:24:16 +0000928 // Compute the KnownZero/KnownOne bits to simplify things downstream.
929 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
930 return 0;
931 }
932
933 // If this is the root being simplified, allow it to have multiple uses,
934 // just set the DemandedMask to all bits so that we can try to simplify the
935 // operands. This allows visitTruncInst (for example) to simplify the
936 // operand of a trunc without duplicating all the logic below.
937 if (Depth == 0 && !V->hasOneUse())
938 DemandedMask = APInt::getAllOnesValue(BitWidth);
939
Reid Spencer8cb68342007-03-12 17:25:59 +0000940 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000941 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000942 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000943 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000944 case Instruction::And:
945 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000946 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
947 RHSKnownZero, RHSKnownOne, Depth+1) ||
948 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000949 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000950 return I;
951 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
952 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000953
954 // If all of the demanded bits are known 1 on one side, return the other.
955 // These bits cannot contribute to the result of the 'and'.
956 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
957 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000958 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000959 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
960 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000961 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000962
963 // If all of the demanded bits in the inputs are known zeros, return zero.
964 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000965 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000966
967 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000968 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000969 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000970
971 // Output known-1 bits are only known if set in both the LHS & RHS.
972 RHSKnownOne &= LHSKnownOne;
973 // Output known-0 are known to be clear if zero in either the LHS | RHS.
974 RHSKnownZero |= LHSKnownZero;
975 break;
976 case Instruction::Or:
977 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000978 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
979 RHSKnownZero, RHSKnownOne, Depth+1) ||
980 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000981 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000982 return I;
983 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
984 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000985
986 // If all of the demanded bits are known zero on one side, return the other.
987 // These bits cannot contribute to the result of the 'or'.
988 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
989 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000990 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000991 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
992 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000993 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000994
995 // If all of the potentially set bits on one side are known to be set on
996 // the other side, just use the 'other' side.
997 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
998 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000999 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001000 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1001 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001002 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001003
1004 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001005 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001006 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001007
1008 // Output known-0 bits are only known if clear in both the LHS & RHS.
1009 RHSKnownZero &= LHSKnownZero;
1010 // Output known-1 are known to be set if set in either the LHS | RHS.
1011 RHSKnownOne |= LHSKnownOne;
1012 break;
1013 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001014 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1015 RHSKnownZero, RHSKnownOne, Depth+1) ||
1016 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001017 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001018 return I;
1019 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1020 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001021
1022 // If all of the demanded bits are known zero on one side, return the other.
1023 // These bits cannot contribute to the result of the 'xor'.
1024 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001025 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001026 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001027 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001028
1029 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1030 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1031 (RHSKnownOne & LHSKnownOne);
1032 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1033 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1034 (RHSKnownOne & LHSKnownZero);
1035
1036 // If all of the demanded bits are known to be zero on one side or the
1037 // other, turn this into an *inclusive* or.
1038 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001039 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1040 Instruction *Or =
1041 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1042 I->getName());
1043 return InsertNewInstBefore(Or, *I);
1044 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001045
1046 // If all of the demanded bits on one side are known, and all of the set
1047 // bits on that side are also known to be set on the other side, turn this
1048 // into an AND, as we know the bits will be cleared.
1049 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1050 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1051 // all known
1052 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001053 Constant *AndC = Constant::getIntegerValue(VTy,
1054 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001055 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001056 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001057 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001058 }
1059 }
1060
1061 // If the RHS is a constant, see if we can simplify it.
1062 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001063 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001064 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001065
Chris Lattnerd0883142009-10-11 22:22:13 +00001066 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1067 // are flipping are known to be set, then the xor is just resetting those
1068 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1069 // simplifying both of them.
1070 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1071 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1072 isa<ConstantInt>(I->getOperand(1)) &&
1073 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1074 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1075 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1076 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1077 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1078
1079 Constant *AndC =
1080 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1081 Instruction *NewAnd =
1082 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1083 InsertNewInstBefore(NewAnd, *I);
1084
1085 Constant *XorC =
1086 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1087 Instruction *NewXor =
1088 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1089 return InsertNewInstBefore(NewXor, *I);
1090 }
1091
1092
Reid Spencer8cb68342007-03-12 17:25:59 +00001093 RHSKnownZero = KnownZeroOut;
1094 RHSKnownOne = KnownOneOut;
1095 break;
1096 }
1097 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001098 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1099 RHSKnownZero, RHSKnownOne, Depth+1) ||
1100 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001101 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001102 return I;
1103 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1104 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001105
1106 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001107 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1108 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001109 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001110
1111 // Only known if known in both the LHS and RHS.
1112 RHSKnownOne &= LHSKnownOne;
1113 RHSKnownZero &= LHSKnownZero;
1114 break;
1115 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001116 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001117 DemandedMask.zext(truncBf);
1118 RHSKnownZero.zext(truncBf);
1119 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001120 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001121 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001122 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001123 DemandedMask.trunc(BitWidth);
1124 RHSKnownZero.trunc(BitWidth);
1125 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001126 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001127 break;
1128 }
1129 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001130 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001131 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001132
1133 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1134 if (const VectorType *SrcVTy =
1135 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1136 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1137 // Don't touch a bitcast between vectors of different element counts.
1138 return false;
1139 } else
1140 // Don't touch a scalar-to-vector bitcast.
1141 return false;
1142 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1143 // Don't touch a vector-to-scalar bitcast.
1144 return false;
1145
Chris Lattner886ab6c2009-01-31 08:15:18 +00001146 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001147 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001148 return I;
1149 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001150 break;
1151 case Instruction::ZExt: {
1152 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001153 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001154
Zhou Shengd48653a2007-03-29 04:45:55 +00001155 DemandedMask.trunc(SrcBitWidth);
1156 RHSKnownZero.trunc(SrcBitWidth);
1157 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001158 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001159 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001160 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001161 DemandedMask.zext(BitWidth);
1162 RHSKnownZero.zext(BitWidth);
1163 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001164 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001165 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001166 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001167 break;
1168 }
1169 case Instruction::SExt: {
1170 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001171 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001172
Reid Spencer8cb68342007-03-12 17:25:59 +00001173 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001174 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001175
Zhou Sheng01542f32007-03-29 02:26:30 +00001176 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001177 // If any of the sign extended bits are demanded, we know that the sign
1178 // bit is demanded.
1179 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001180 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001181
Zhou Shengd48653a2007-03-29 04:45:55 +00001182 InputDemandedBits.trunc(SrcBitWidth);
1183 RHSKnownZero.trunc(SrcBitWidth);
1184 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001185 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001186 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001187 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001188 InputDemandedBits.zext(BitWidth);
1189 RHSKnownZero.zext(BitWidth);
1190 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001191 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001192
1193 // If the sign bit of the input is known set or clear, then we know the
1194 // top bits of the result.
1195
1196 // If the input sign bit is known zero, or if the NewBits are not demanded
1197 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001198 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001199 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001200 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1201 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001202 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001203 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001204 }
1205 break;
1206 }
1207 case Instruction::Add: {
1208 // Figure out what the input bits are. If the top bits of the and result
1209 // are not demanded, then the add doesn't demand them from its input
1210 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001211 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001212
1213 // If there is a constant on the RHS, there are a variety of xformations
1214 // we can do.
1215 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1216 // If null, this should be simplified elsewhere. Some of the xforms here
1217 // won't work if the RHS is zero.
1218 if (RHS->isZero())
1219 break;
1220
1221 // If the top bit of the output is demanded, demand everything from the
1222 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001223 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001224
1225 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001226 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001227 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001228 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001229
1230 // If the RHS of the add has bits set that can't affect the input, reduce
1231 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001232 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001233 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001234
1235 // Avoid excess work.
1236 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1237 break;
1238
1239 // Turn it into OR if input bits are zero.
1240 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1241 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001242 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001243 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001244 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001245 }
1246
1247 // We can say something about the output known-zero and known-one bits,
1248 // depending on potential carries from the input constant and the
1249 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1250 // bits set and the RHS constant is 0x01001, then we know we have a known
1251 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1252
1253 // To compute this, we first compute the potential carry bits. These are
1254 // the bits which may be modified. I'm not aware of a better way to do
1255 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001256 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001257 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001258
1259 // Now that we know which bits have carries, compute the known-1/0 sets.
1260
1261 // Bits are known one if they are known zero in one operand and one in the
1262 // other, and there is no input carry.
1263 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1264 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1265
1266 // Bits are known zero if they are known zero in both operands and there
1267 // is no input carry.
1268 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1269 } else {
1270 // If the high-bits of this ADD are not demanded, then it does not demand
1271 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001272 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001273 // Right fill the mask of bits for this ADD to demand the most
1274 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001275 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001276 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1277 LHSKnownZero, LHSKnownOne, Depth+1) ||
1278 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001279 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001280 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001281 }
1282 }
1283 break;
1284 }
1285 case Instruction::Sub:
1286 // If the high-bits of this SUB are not demanded, then it does not demand
1287 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001288 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001289 // Right fill the mask of bits for this SUB to demand the most
1290 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001291 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001292 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001293 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1294 LHSKnownZero, LHSKnownOne, Depth+1) ||
1295 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001296 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001297 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001298 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001299 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1300 // the known zeros and ones.
1301 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001302 break;
1303 case Instruction::Shl:
1304 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001305 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001306 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001307 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001308 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001309 return I;
1310 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001311 RHSKnownZero <<= ShiftAmt;
1312 RHSKnownOne <<= ShiftAmt;
1313 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001314 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001315 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001316 }
1317 break;
1318 case Instruction::LShr:
1319 // For a logical shift right
1320 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001321 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001322
Reid Spencer8cb68342007-03-12 17:25:59 +00001323 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001324 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001325 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001326 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001327 return I;
1328 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001329 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1330 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001331 if (ShiftAmt) {
1332 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001333 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001334 RHSKnownZero |= HighBits; // high bits known zero.
1335 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001336 }
1337 break;
1338 case Instruction::AShr:
1339 // If this is an arithmetic shift right and only the low-bit is set, we can
1340 // always convert this into a logical shr, even if the shift amount is
1341 // variable. The low bit of the shift cannot be an input sign bit unless
1342 // the shift amount is >= the size of the datatype, which is undefined.
1343 if (DemandedMask == 1) {
1344 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001345 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001346 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001347 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001348 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001349
1350 // If the sign bit is the only bit demanded by this ashr, then there is no
1351 // need to do it, the shift doesn't change the high bit.
1352 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001353 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001354
1355 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001356 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001357
Reid Spencer8cb68342007-03-12 17:25:59 +00001358 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001359 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001360 // If any of the "high bits" are demanded, we should set the sign bit as
1361 // demanded.
1362 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1363 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001364 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001365 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001366 return I;
1367 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001368 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001369 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001370 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1371 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1372
1373 // Handle the sign bits.
1374 APInt SignBit(APInt::getSignBit(BitWidth));
1375 // Adjust to where it is now in the mask.
1376 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1377
1378 // If the input sign bit is known to be zero, or if none of the top bits
1379 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001380 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001381 (HighBits & ~DemandedMask) == HighBits) {
1382 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001383 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001384 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001385 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001386 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1387 RHSKnownOne |= HighBits;
1388 }
1389 }
1390 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001391 case Instruction::SRem:
1392 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001393 APInt RA = Rem->getValue().abs();
1394 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001395 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001396 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001397
Nick Lewycky8e394322008-11-02 02:41:50 +00001398 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001399 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001400 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001401 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001402 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001403
1404 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1405 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001406
1407 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001408
Chris Lattner886ab6c2009-01-31 08:15:18 +00001409 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001410 }
1411 }
1412 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001413 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001414 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1415 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001416 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1417 KnownZero2, KnownOne2, Depth+1) ||
1418 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001419 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001420 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001421
Chris Lattner455e9ab2009-01-21 18:09:24 +00001422 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001423 Leaders = std::max(Leaders,
1424 KnownZero2.countLeadingOnes());
1425 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001426 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001427 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001428 case Instruction::Call:
1429 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1430 switch (II->getIntrinsicID()) {
1431 default: break;
1432 case Intrinsic::bswap: {
1433 // If the only bits demanded come from one byte of the bswap result,
1434 // just shift the input byte into position to eliminate the bswap.
1435 unsigned NLZ = DemandedMask.countLeadingZeros();
1436 unsigned NTZ = DemandedMask.countTrailingZeros();
1437
1438 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1439 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1440 // have 14 leading zeros, round to 8.
1441 NLZ &= ~7;
1442 NTZ &= ~7;
1443 // If we need exactly one byte, we can do this transformation.
1444 if (BitWidth-NLZ-NTZ == 8) {
1445 unsigned ResultBit = NTZ;
1446 unsigned InputBit = BitWidth-NTZ-8;
1447
1448 // Replace this with either a left or right shift to get the byte into
1449 // the right place.
1450 Instruction *NewVal;
1451 if (InputBit > ResultBit)
1452 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001453 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001454 else
1455 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001456 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001457 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001458 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001459 }
1460
1461 // TODO: Could compute known zero/one bits based on the input.
1462 break;
1463 }
1464 }
1465 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001466 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001467 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001468 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001469
1470 // If the client is only demanding bits that we know, return the known
1471 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001472 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1473 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001474 return false;
1475}
1476
Chris Lattner867b99f2006-10-05 06:55:50 +00001477
Mon P Wangaeb06d22008-11-10 04:46:22 +00001478/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001479/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001480/// actually used by the caller. This method analyzes which elements of the
1481/// operand are undef and returns that information in UndefElts.
1482///
1483/// If the information about demanded elements can be used to simplify the
1484/// operation, the operation is simplified, then the resultant value is
1485/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001486Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1487 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001488 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001489 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001490 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001491 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001492
1493 if (isa<UndefValue>(V)) {
1494 // If the entire vector is undefined, just return this info.
1495 UndefElts = EltMask;
1496 return 0;
1497 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1498 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001499 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001500 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001501
Chris Lattner867b99f2006-10-05 06:55:50 +00001502 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001503 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1504 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001505 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001506
1507 std::vector<Constant*> Elts;
1508 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001509 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001510 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001511 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001512 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1513 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001514 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001515 } else { // Otherwise, defined.
1516 Elts.push_back(CP->getOperand(i));
1517 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001518
Chris Lattner867b99f2006-10-05 06:55:50 +00001519 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001520 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001521 return NewCP != CP ? NewCP : 0;
1522 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001523 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001524 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001525
1526 // Check if this is identity. If so, return 0 since we are not simplifying
1527 // anything.
1528 if (DemandedElts == ((1ULL << VWidth) -1))
1529 return 0;
1530
Reid Spencer9d6565a2007-02-15 02:26:10 +00001531 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001532 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001533 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001534 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001535 for (unsigned i = 0; i != VWidth; ++i) {
1536 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1537 Elts.push_back(Elt);
1538 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001539 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001540 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001541 }
1542
Dan Gohman488fbfc2008-09-09 18:11:14 +00001543 // Limit search depth.
1544 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001545 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001546
1547 // If multiple users are using the root value, procede with
1548 // simplification conservatively assuming that all elements
1549 // are needed.
1550 if (!V->hasOneUse()) {
1551 // Quit if we find multiple users of a non-root value though.
1552 // They'll be handled when it's their turn to be visited by
1553 // the main instcombine process.
1554 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001555 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001556 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001557
1558 // Conservatively assume that all elements are needed.
1559 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001560 }
1561
1562 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001563 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001564
1565 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001566 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001567 Value *TmpV;
1568 switch (I->getOpcode()) {
1569 default: break;
1570
1571 case Instruction::InsertElement: {
1572 // If this is a variable index, we don't know which element it overwrites.
1573 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001574 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001575 if (Idx == 0) {
1576 // Note that we can't propagate undef elt info, because we don't know
1577 // which elt is getting updated.
1578 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1579 UndefElts2, Depth+1);
1580 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1581 break;
1582 }
1583
1584 // If this is inserting an element that isn't demanded, remove this
1585 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001586 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001587 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1588 Worklist.Add(I);
1589 return I->getOperand(0);
1590 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001591
1592 // Otherwise, the element inserted overwrites whatever was there, so the
1593 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001594 APInt DemandedElts2 = DemandedElts;
1595 DemandedElts2.clear(IdxNo);
1596 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001597 UndefElts, Depth+1);
1598 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1599
1600 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001601 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001602 break;
1603 }
1604 case Instruction::ShuffleVector: {
1605 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001606 uint64_t LHSVWidth =
1607 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001608 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001609 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001610 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001611 unsigned MaskVal = Shuffle->getMaskValue(i);
1612 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001613 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001614 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001615 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001616 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001617 else
Evan Cheng388df622009-02-03 10:05:09 +00001618 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001619 }
1620 }
1621 }
1622
Nate Begeman7b254672009-02-11 22:36:25 +00001623 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001624 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001625 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001626 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1627
Nate Begeman7b254672009-02-11 22:36:25 +00001628 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001629 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1630 UndefElts3, Depth+1);
1631 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1632
1633 bool NewUndefElts = false;
1634 for (unsigned i = 0; i < VWidth; i++) {
1635 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001636 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001637 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001638 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001639 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001640 NewUndefElts = true;
1641 UndefElts.set(i);
1642 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001643 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001644 if (UndefElts3[MaskVal - LHSVWidth]) {
1645 NewUndefElts = true;
1646 UndefElts.set(i);
1647 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001648 }
1649 }
1650
1651 if (NewUndefElts) {
1652 // Add additional discovered undefs.
1653 std::vector<Constant*> Elts;
1654 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001655 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001656 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001657 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001658 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001659 Shuffle->getMaskValue(i)));
1660 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001661 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001662 MadeChange = true;
1663 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001664 break;
1665 }
Chris Lattner69878332007-04-14 22:29:23 +00001666 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001667 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001668 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1669 if (!VTy) break;
1670 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001671 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001672 unsigned Ratio;
1673
1674 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001675 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001676 // elements as are demanded of us.
1677 Ratio = 1;
1678 InputDemandedElts = DemandedElts;
1679 } else if (VWidth > InVWidth) {
1680 // Untested so far.
1681 break;
1682
1683 // If there are more elements in the result than there are in the source,
1684 // then an input element is live if any of the corresponding output
1685 // elements are live.
1686 Ratio = VWidth/InVWidth;
1687 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001688 if (DemandedElts[OutIdx])
1689 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001690 }
1691 } else {
1692 // Untested so far.
1693 break;
1694
1695 // If there are more elements in the source than there are in the result,
1696 // then an input element is live if the corresponding output element is
1697 // live.
1698 Ratio = InVWidth/VWidth;
1699 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001700 if (DemandedElts[InIdx/Ratio])
1701 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001702 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001703
Chris Lattner69878332007-04-14 22:29:23 +00001704 // div/rem demand all inputs, because they don't want divide by zero.
1705 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1706 UndefElts2, Depth+1);
1707 if (TmpV) {
1708 I->setOperand(0, TmpV);
1709 MadeChange = true;
1710 }
1711
1712 UndefElts = UndefElts2;
1713 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001714 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001715 // If there are more elements in the result than there are in the source,
1716 // then an output element is undef if the corresponding input element is
1717 // undef.
1718 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001719 if (UndefElts2[OutIdx/Ratio])
1720 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001721 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001722 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001723 // If there are more elements in the source than there are in the result,
1724 // then a result element is undef if all of the corresponding input
1725 // elements are undef.
1726 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1727 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001728 if (!UndefElts2[InIdx]) // Not undef?
1729 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001730 }
1731 break;
1732 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001733 case Instruction::And:
1734 case Instruction::Or:
1735 case Instruction::Xor:
1736 case Instruction::Add:
1737 case Instruction::Sub:
1738 case Instruction::Mul:
1739 // div/rem demand all inputs, because they don't want divide by zero.
1740 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1741 UndefElts, Depth+1);
1742 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1743 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1744 UndefElts2, Depth+1);
1745 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1746
1747 // Output elements are undefined if both are undefined. Consider things
1748 // like undef&0. The result is known zero, not undef.
1749 UndefElts &= UndefElts2;
1750 break;
1751
1752 case Instruction::Call: {
1753 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1754 if (!II) break;
1755 switch (II->getIntrinsicID()) {
1756 default: break;
1757
1758 // Binary vector operations that work column-wise. A dest element is a
1759 // function of the corresponding input elements from the two inputs.
1760 case Intrinsic::x86_sse_sub_ss:
1761 case Intrinsic::x86_sse_mul_ss:
1762 case Intrinsic::x86_sse_min_ss:
1763 case Intrinsic::x86_sse_max_ss:
1764 case Intrinsic::x86_sse2_sub_sd:
1765 case Intrinsic::x86_sse2_mul_sd:
1766 case Intrinsic::x86_sse2_min_sd:
1767 case Intrinsic::x86_sse2_max_sd:
1768 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1769 UndefElts, Depth+1);
1770 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1771 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1772 UndefElts2, Depth+1);
1773 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1774
1775 // If only the low elt is demanded and this is a scalarizable intrinsic,
1776 // scalarize it now.
1777 if (DemandedElts == 1) {
1778 switch (II->getIntrinsicID()) {
1779 default: break;
1780 case Intrinsic::x86_sse_sub_ss:
1781 case Intrinsic::x86_sse_mul_ss:
1782 case Intrinsic::x86_sse2_sub_sd:
1783 case Intrinsic::x86_sse2_mul_sd:
1784 // TODO: Lower MIN/MAX/ABS/etc
1785 Value *LHS = II->getOperand(1);
1786 Value *RHS = II->getOperand(2);
1787 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001788 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001789 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001790 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001791 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001792
1793 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001794 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001795 case Intrinsic::x86_sse_sub_ss:
1796 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001797 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001798 II->getName()), *II);
1799 break;
1800 case Intrinsic::x86_sse_mul_ss:
1801 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001802 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001803 II->getName()), *II);
1804 break;
1805 }
1806
1807 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001808 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001809 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001810 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001811 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001812 return New;
1813 }
1814 }
1815
1816 // Output elements are undefined if both are undefined. Consider things
1817 // like undef&0. The result is known zero, not undef.
1818 UndefElts &= UndefElts2;
1819 break;
1820 }
1821 break;
1822 }
1823 }
1824 return MadeChange ? I : 0;
1825}
1826
Dan Gohman45b4e482008-05-19 22:14:15 +00001827
Chris Lattner564a7272003-08-13 19:01:45 +00001828/// AssociativeOpt - Perform an optimization on an associative operator. This
1829/// function is designed to check a chain of associative operators for a
1830/// potential to apply a certain optimization. Since the optimization may be
1831/// applicable if the expression was reassociated, this checks the chain, then
1832/// reassociates the expression as necessary to expose the optimization
1833/// opportunity. This makes use of a special Functor, which must define
1834/// 'shouldApply' and 'apply' methods.
1835///
1836template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001837static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001838 unsigned Opcode = Root.getOpcode();
1839 Value *LHS = Root.getOperand(0);
1840
1841 // Quick check, see if the immediate LHS matches...
1842 if (F.shouldApply(LHS))
1843 return F.apply(Root);
1844
1845 // Otherwise, if the LHS is not of the same opcode as the root, return.
1846 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001847 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001848 // Should we apply this transform to the RHS?
1849 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1850
1851 // If not to the RHS, check to see if we should apply to the LHS...
1852 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1853 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1854 ShouldApply = true;
1855 }
1856
1857 // If the functor wants to apply the optimization to the RHS of LHSI,
1858 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1859 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001860 // Now all of the instructions are in the current basic block, go ahead
1861 // and perform the reassociation.
1862 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1863
1864 // First move the selected RHS to the LHS of the root...
1865 Root.setOperand(0, LHSI->getOperand(1));
1866
1867 // Make what used to be the LHS of the root be the user of the root...
1868 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001869 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001870 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001871 return 0;
1872 }
Chris Lattner65725312004-04-16 18:08:07 +00001873 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001874 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001875 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001876 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001877 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001878
1879 // Now propagate the ExtraOperand down the chain of instructions until we
1880 // get to LHSI.
1881 while (TmpLHSI != LHSI) {
1882 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001883 // Move the instruction to immediately before the chain we are
1884 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001885 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001886 ARI = NextLHSI;
1887
Chris Lattner564a7272003-08-13 19:01:45 +00001888 Value *NextOp = NextLHSI->getOperand(1);
1889 NextLHSI->setOperand(1, ExtraOperand);
1890 TmpLHSI = NextLHSI;
1891 ExtraOperand = NextOp;
1892 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001893
Chris Lattner564a7272003-08-13 19:01:45 +00001894 // Now that the instructions are reassociated, have the functor perform
1895 // the transformation...
1896 return F.apply(Root);
1897 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001898
Chris Lattner564a7272003-08-13 19:01:45 +00001899 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1900 }
1901 return 0;
1902}
1903
Dan Gohman844731a2008-05-13 00:00:25 +00001904namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001905
Nick Lewycky02d639f2008-05-23 04:34:58 +00001906// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001907struct AddRHS {
1908 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001909 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001910 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1911 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001912 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001913 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001914 }
1915};
1916
1917// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1918// iff C1&C2 == 0
1919struct AddMaskingAnd {
1920 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001921 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001922 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001923 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001924 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001925 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001926 }
1927 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001928 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001929 }
1930};
1931
Dan Gohman844731a2008-05-13 00:00:25 +00001932}
1933
Chris Lattner6e7ba452005-01-01 16:22:27 +00001934static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001935 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001936 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001937 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001938
Chris Lattner2eefe512004-04-09 19:05:30 +00001939 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001940 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1941 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001942
Chris Lattner2eefe512004-04-09 19:05:30 +00001943 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1944 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001945 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1946 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001947 }
1948
1949 Value *Op0 = SO, *Op1 = ConstOperand;
1950 if (!ConstIsRHS)
1951 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001952
Chris Lattner6e7ba452005-01-01 16:22:27 +00001953 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001954 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1955 SO->getName()+".op");
1956 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1957 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1958 SO->getName()+".cmp");
1959 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1960 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1961 SO->getName()+".cmp");
1962 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001963}
1964
1965// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1966// constant as the other operand, try to fold the binary operator into the
1967// select arguments. This also works for Cast instructions, which obviously do
1968// not have a second operand.
1969static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1970 InstCombiner *IC) {
1971 // Don't modify shared select instructions
1972 if (!SI->hasOneUse()) return 0;
1973 Value *TV = SI->getOperand(1);
1974 Value *FV = SI->getOperand(2);
1975
1976 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001977 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00001978 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001979
Chris Lattner6e7ba452005-01-01 16:22:27 +00001980 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1981 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1982
Gabor Greif051a9502008-04-06 20:25:17 +00001983 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1984 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001985 }
1986 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001987}
1988
Chris Lattner4e998b22004-09-29 05:07:12 +00001989
Chris Lattner5d1704d2009-09-27 19:57:57 +00001990/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
1991/// has a PHI node as operand #0, see if we can fold the instruction into the
1992/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00001993///
1994/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
1995/// that would normally be unprofitable because they strongly encourage jump
1996/// threading.
1997Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
1998 bool AllowAggressive) {
1999 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00002000 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002001 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00002002 if (NumPHIValues == 0 ||
2003 // We normally only transform phis with a single use, unless we're trying
2004 // hard to make jump threading happen.
2005 (!PN->hasOneUse() && !AllowAggressive))
2006 return 0;
2007
2008
Chris Lattner5d1704d2009-09-27 19:57:57 +00002009 // Check to see if all of the operands of the PHI are simple constants
2010 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002011 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2012 // bail out. We don't do arbitrary constant expressions here because moving
2013 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002014 BasicBlock *NonConstBB = 0;
2015 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00002016 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2017 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002018 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002019 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002020 NonConstBB = PN->getIncomingBlock(i);
2021
2022 // If the incoming non-constant value is in I's block, we have an infinite
2023 // loop.
2024 if (NonConstBB == I.getParent())
2025 return 0;
2026 }
2027
2028 // If there is exactly one non-constant value, we can insert a copy of the
2029 // operation in that block. However, if this is a critical edge, we would be
2030 // inserting the computation one some other paths (e.g. inside a loop). Only
2031 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00002032 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002033 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2034 if (!BI || !BI->isUnconditional()) return 0;
2035 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002036
2037 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002038 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002039 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +00002040 InsertNewInstBefore(NewPN, *PN);
2041 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002042
2043 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00002044 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2045 // We only currently try to fold the condition of a select when it is a phi,
2046 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002047 Value *TrueV = SI->getTrueValue();
2048 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002049 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002050 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002051 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002052 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2053 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002054 Value *InV = 0;
2055 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002056 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002057 } else {
2058 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002059 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2060 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002061 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002062 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +00002063 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002064 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002065 }
2066 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002067 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002068 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002069 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002070 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002071 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002072 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002073 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002074 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002075 } else {
2076 assert(PN->getIncomingBlock(i) == NonConstBB);
2077 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002078 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002079 PN->getIncomingValue(i), C, "phitmp",
2080 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002081 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002082 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002083 CI->getPredicate(),
2084 PN->getIncomingValue(i), C, "phitmp",
2085 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002086 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002087 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +00002088
2089 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002090 }
2091 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002092 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002093 } else {
2094 CastInst *CI = cast<CastInst>(&I);
2095 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002096 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002097 Value *InV;
2098 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002099 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002100 } else {
2101 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002102 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002103 I.getType(), "phitmp",
2104 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002105 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002106 }
2107 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002108 }
2109 }
2110 return ReplaceInstUsesWith(I, NewPN);
2111}
2112
Chris Lattner2454a2e2008-01-29 06:52:45 +00002113
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002114/// WillNotOverflowSignedAdd - Return true if we can prove that:
2115/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2116/// This basically requires proving that the add in the original type would not
2117/// overflow to change the sign bit or have a carry out.
2118bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2119 // There are different heuristics we can use for this. Here are some simple
2120 // ones.
2121
2122 // Add has the property that adding any two 2's complement numbers can only
2123 // have one carry bit which can change a sign. As such, if LHS and RHS each
2124 // have at least two sign bits, we know that the addition of the two values will
2125 // sign extend fine.
2126 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2127 return true;
2128
2129
2130 // If one of the operands only has one non-zero bit, and if the other operand
2131 // has a known-zero bit in a more significant place than it (not including the
2132 // sign bit) the ripple may go up to and fill the zero, but won't change the
2133 // sign. For example, (X & ~4) + 1.
2134
2135 // TODO: Implement.
2136
2137 return false;
2138}
2139
Chris Lattner2454a2e2008-01-29 06:52:45 +00002140
Chris Lattner7e708292002-06-25 16:13:24 +00002141Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002142 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002143 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002144
Chris Lattner66331a42004-04-10 22:01:55 +00002145 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002146 // X + undef -> undef
2147 if (isa<UndefValue>(RHS))
2148 return ReplaceInstUsesWith(I, RHS);
2149
Chris Lattner66331a42004-04-10 22:01:55 +00002150 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002151 if (RHSC->isNullValue())
2152 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002153
Chris Lattner66331a42004-04-10 22:01:55 +00002154 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002155 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002156 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002157 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002158 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002159 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002160
2161 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2162 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002163 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002164 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002165
Eli Friedman709b33d2009-07-13 22:27:52 +00002166 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002167 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002168 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002169 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002170 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002171
2172 if (isa<PHINode>(LHS))
2173 if (Instruction *NV = FoldOpIntoPhi(I))
2174 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002175
Chris Lattner4f637d42006-01-06 17:59:59 +00002176 ConstantInt *XorRHS = 0;
2177 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002178 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002179 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002180 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002181 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002182
Zhou Sheng4351c642007-04-02 08:20:41 +00002183 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002184 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2185 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002186 do {
2187 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002188 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2189 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002190 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2191 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002192 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002193 if (!MaskedValueIsZero(XorLHS,
2194 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002195 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002196 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002197 }
2198 }
2199 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002200 C0080Val = APIntOps::lshr(C0080Val, Size);
2201 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2202 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002203
Reid Spencer35c38852007-03-28 01:36:16 +00002204 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002205 // with funny bit widths then this switch statement should be removed. It
2206 // is just here to get the size of the "middle" type back up to something
2207 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002208 const Type *MiddleType = 0;
2209 switch (Size) {
2210 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002211 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2212 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2213 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002214 }
2215 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002216 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002217 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002218 }
2219 }
Chris Lattner66331a42004-04-10 22:01:55 +00002220 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002221
Owen Anderson1d0be152009-08-13 21:58:54 +00002222 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002223 return BinaryOperator::CreateXor(LHS, RHS);
2224
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002225 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002226 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002227 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002228 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002229
2230 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2231 if (RHSI->getOpcode() == Instruction::Sub)
2232 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2233 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2234 }
2235 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2236 if (LHSI->getOpcode() == Instruction::Sub)
2237 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2238 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2239 }
Robert Bocchino71698282004-07-27 21:02:21 +00002240 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002241
Chris Lattner5c4afb92002-05-08 22:46:53 +00002242 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002243 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002244 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002245 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002246 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002247 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002248 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002249 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002250 }
2251
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002252 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002253 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002254
2255 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002256 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002257 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002258 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002259
Misha Brukmanfd939082005-04-21 23:48:37 +00002260
Chris Lattner50af16a2004-11-13 19:50:12 +00002261 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002262 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002263 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002264 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002265
2266 // X*C1 + X*C2 --> X * (C1+C2)
2267 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002268 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002269 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002270 }
2271
2272 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002273 if (dyn_castFoldableMul(RHS, C2) == LHS)
2274 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002275
Chris Lattnere617c9e2007-01-05 02:17:46 +00002276 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002277 if (dyn_castNotVal(LHS) == RHS ||
2278 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002279 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002280
Chris Lattnerad3448c2003-02-18 19:57:07 +00002281
Chris Lattner564a7272003-08-13 19:01:45 +00002282 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002283 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2284 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002285 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002286
2287 // A+B --> A|B iff A and B have no bits set in common.
2288 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2289 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2290 APInt LHSKnownOne(IT->getBitWidth(), 0);
2291 APInt LHSKnownZero(IT->getBitWidth(), 0);
2292 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2293 if (LHSKnownZero != 0) {
2294 APInt RHSKnownOne(IT->getBitWidth(), 0);
2295 APInt RHSKnownZero(IT->getBitWidth(), 0);
2296 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2297
2298 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002299 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002300 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002301 }
2302 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002303
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002304 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002305 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002306 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002307 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2308 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002309 if (W != Y) {
2310 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002311 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002312 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002313 std::swap(W, X);
2314 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002315 std::swap(Y, Z);
2316 std::swap(W, X);
2317 }
2318 }
2319
2320 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002321 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002322 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002323 }
2324 }
2325 }
2326
Chris Lattner6b032052003-10-02 15:11:26 +00002327 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002328 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002329 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002330 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002331
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002332 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002333 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002334 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002335 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002336 if (Anded == CRHS) {
2337 // See if all bits from the first bit set in the Add RHS up are included
2338 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002339 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002340
2341 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002342 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002343
2344 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002345 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002346
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002347 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2348 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002349 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002350 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002351 }
2352 }
2353 }
2354
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002355 // Try to fold constant add into select arguments.
2356 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002357 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002358 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002359 }
2360
Chris Lattner42790482007-12-20 01:56:58 +00002361 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002362 {
2363 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002364 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002365 if (!SI) {
2366 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002367 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002368 }
Chris Lattner42790482007-12-20 01:56:58 +00002369 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002370 Value *TV = SI->getTrueValue();
2371 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002372 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002373
2374 // Can we fold the add into the argument of the select?
2375 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002376 if (match(FV, m_Zero()) &&
2377 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002378 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002379 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002380 if (match(TV, m_Zero()) &&
2381 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002382 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002383 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002384 }
2385 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002386
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002387 // Check for (add (sext x), y), see if we can merge this into an
2388 // integer add followed by a sext.
2389 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2390 // (add (sext x), cst) --> (sext (add x, cst'))
2391 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2392 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002393 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002394 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002395 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002396 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2397 // Insert the new, smaller add.
Chris Lattner74381062009-08-30 07:44:24 +00002398 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2399 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002400 return new SExtInst(NewAdd, I.getType());
2401 }
2402 }
2403
2404 // (add (sext x), (sext y)) --> (sext (add int x, y))
2405 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2406 // Only do this if x/y have the same type, if at last one of them has a
2407 // single use (so we don't increase the number of sexts), and if the
2408 // integer add will not overflow.
2409 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2410 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2411 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2412 RHSConv->getOperand(0))) {
2413 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002414 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2415 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002416 return new SExtInst(NewAdd, I.getType());
2417 }
2418 }
2419 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002420
2421 return Changed ? &I : 0;
2422}
2423
2424Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2425 bool Changed = SimplifyCommutative(I);
2426 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2427
2428 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2429 // X + 0 --> X
2430 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002431 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002432 (I.getType())->getValueAPF()))
2433 return ReplaceInstUsesWith(I, LHS);
2434 }
2435
2436 if (isa<PHINode>(LHS))
2437 if (Instruction *NV = FoldOpIntoPhi(I))
2438 return NV;
2439 }
2440
2441 // -A + B --> B - A
2442 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002443 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002444 return BinaryOperator::CreateFSub(RHS, LHSV);
2445
2446 // A + -B --> A - B
2447 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002448 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002449 return BinaryOperator::CreateFSub(LHS, V);
2450
2451 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2452 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2453 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2454 return ReplaceInstUsesWith(I, LHS);
2455
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002456 // Check for (add double (sitofp x), y), see if we can merge this into an
2457 // integer add followed by a promotion.
2458 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2459 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2460 // ... if the constant fits in the integer value. This is useful for things
2461 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2462 // requires a constant pool load, and generally allows the add to be better
2463 // instcombined.
2464 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2465 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002466 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002467 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002468 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002469 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2470 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002471 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2472 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002473 return new SIToFPInst(NewAdd, I.getType());
2474 }
2475 }
2476
2477 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2478 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2479 // Only do this if x/y have the same type, if at last one of them has a
2480 // single use (so we don't increase the number of int->fp conversions),
2481 // and if the integer add will not overflow.
2482 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2483 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2484 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2485 RHSConv->getOperand(0))) {
2486 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002487 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2488 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002489 return new SIToFPInst(NewAdd, I.getType());
2490 }
2491 }
2492 }
2493
Chris Lattner7e708292002-06-25 16:13:24 +00002494 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002495}
2496
Chris Lattner7e708292002-06-25 16:13:24 +00002497Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002498 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002499
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002500 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002501 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002502
Chris Lattner233f7dc2002-08-12 21:17:25 +00002503 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002504 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002505 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002506
Chris Lattnere87597f2004-10-16 18:11:37 +00002507 if (isa<UndefValue>(Op0))
2508 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2509 if (isa<UndefValue>(Op1))
2510 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2511
Chris Lattnerd65460f2003-11-05 01:06:05 +00002512 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2513 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002514 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002515 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002516
Chris Lattnerd65460f2003-11-05 01:06:05 +00002517 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002518 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002519 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002520 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002521
Chris Lattner76b7a062007-01-15 07:02:54 +00002522 // -(X >>u 31) -> (X >>s 31)
2523 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002524 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002525 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002526 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002527 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002528 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002529 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002530 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002531 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002532 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002533 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002534 }
2535 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002536 }
2537 else if (SI->getOpcode() == Instruction::AShr) {
2538 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2539 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002540 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002541 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002542 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002543 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002544 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002545 }
2546 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002547 }
2548 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002549 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002550
2551 // Try to fold constant sub into select arguments.
2552 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002553 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002554 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002555
2556 // C - zext(bool) -> bool ? C - 1 : C
2557 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002558 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002559 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002560 }
2561
Owen Anderson1d0be152009-08-13 21:58:54 +00002562 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002563 return BinaryOperator::CreateXor(Op0, Op1);
2564
Chris Lattner43d84d62005-04-07 16:15:25 +00002565 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002566 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002567 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002568 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002569 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002570 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002571 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002572 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002573 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2574 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2575 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002576 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002577 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002578 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002579 }
2580
Chris Lattnerfd059242003-10-15 16:48:29 +00002581 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002582 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2583 // is not used by anyone else...
2584 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002585 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002586 // Swap the two operands of the subexpr...
2587 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2588 Op1I->setOperand(0, IIOp1);
2589 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002590
Chris Lattnera2881962003-02-18 19:28:33 +00002591 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002592 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002593 }
2594
2595 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2596 //
2597 if (Op1I->getOpcode() == Instruction::And &&
2598 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2599 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2600
Chris Lattner74381062009-08-30 07:44:24 +00002601 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002602 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002603 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002604
Reid Spencerac5209e2006-10-16 23:08:08 +00002605 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002606 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002607 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002608 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002609 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002610 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002611 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002612
Chris Lattnerad3448c2003-02-18 19:57:07 +00002613 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002614 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002615 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002616 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002617 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002618 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002619 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002620 }
Chris Lattner40371712002-05-09 01:29:19 +00002621 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002622 }
Chris Lattnera2881962003-02-18 19:28:33 +00002623
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002624 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2625 if (Op0I->getOpcode() == Instruction::Add) {
2626 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2627 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2628 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2629 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2630 } else if (Op0I->getOpcode() == Instruction::Sub) {
2631 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002632 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002633 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002634 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002635 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002636
Chris Lattner50af16a2004-11-13 19:50:12 +00002637 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002638 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002639 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002640 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002641
Chris Lattner50af16a2004-11-13 19:50:12 +00002642 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002643 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002644 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002645 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002646 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002647}
2648
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002649Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2650 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2651
2652 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002653 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002654 return BinaryOperator::CreateFAdd(Op0, V);
2655
2656 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2657 if (Op1I->getOpcode() == Instruction::FAdd) {
2658 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002659 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002660 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002661 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002662 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002663 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002664 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002665 }
2666
2667 return 0;
2668}
2669
Chris Lattnera0141b92007-07-15 20:42:37 +00002670/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2671/// comparison only checks the sign bit. If it only checks the sign bit, set
2672/// TrueIfSigned if the result of the comparison is true when the input value is
2673/// signed.
2674static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2675 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002676 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002677 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2678 TrueIfSigned = true;
2679 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002680 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2681 TrueIfSigned = true;
2682 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002683 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2684 TrueIfSigned = false;
2685 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002686 case ICmpInst::ICMP_UGT:
2687 // True if LHS u> RHS and RHS == high-bit-mask - 1
2688 TrueIfSigned = true;
2689 return RHS->getValue() ==
2690 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2691 case ICmpInst::ICMP_UGE:
2692 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2693 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002694 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002695 default:
2696 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002697 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002698}
2699
Chris Lattner7e708292002-06-25 16:13:24 +00002700Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002701 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002702 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002703
Chris Lattnera2498472009-10-11 21:36:10 +00002704 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002705 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002706
Chris Lattner8af304a2009-10-11 07:53:15 +00002707 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00002708 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2709 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002710
2711 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002712 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002713 if (SI->getOpcode() == Instruction::Shl)
2714 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002715 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002716 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002717
Zhou Sheng843f07672007-04-19 05:39:12 +00002718 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00002719 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00002720 if (CI->equalsInt(1)) // X * 1 == X
2721 return ReplaceInstUsesWith(I, Op0);
2722 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002723 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002724
Zhou Sheng97b52c22007-03-29 01:57:21 +00002725 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002726 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002727 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002728 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002729 }
Chris Lattnera2498472009-10-11 21:36:10 +00002730 } else if (isa<VectorType>(Op1C->getType())) {
2731 if (Op1C->isNullValue())
2732 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00002733
Chris Lattnera2498472009-10-11 21:36:10 +00002734 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002735 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002736 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002737
2738 // As above, vector X*splat(1.0) -> X in all defined cases.
2739 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002740 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2741 if (CI->equalsInt(1))
2742 return ReplaceInstUsesWith(I, Op0);
2743 }
2744 }
Chris Lattnera2881962003-02-18 19:28:33 +00002745 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002746
2747 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2748 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00002749 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002750 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00002751 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2752 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002753 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002754
2755 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002756
2757 // Try to fold constant mul into select arguments.
2758 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002759 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002760 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002761
2762 if (isa<PHINode>(Op0))
2763 if (Instruction *NV = FoldOpIntoPhi(I))
2764 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002765 }
2766
Dan Gohman186a6362009-08-12 16:04:34 +00002767 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00002768 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002769 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002770
Nick Lewycky0c730792008-11-21 07:33:58 +00002771 // (X / Y) * Y = X - (X % Y)
2772 // (X / Y) * -Y = (X % Y) - X
2773 {
Chris Lattnera2498472009-10-11 21:36:10 +00002774 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00002775 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2776 if (!BO ||
2777 (BO->getOpcode() != Instruction::UDiv &&
2778 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00002779 Op1C = Op0;
2780 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002781 }
Chris Lattnera2498472009-10-11 21:36:10 +00002782 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00002783 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00002784 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00002785 (BO->getOpcode() == Instruction::UDiv ||
2786 BO->getOpcode() == Instruction::SDiv)) {
2787 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2788
Dan Gohmanfa94b942009-08-12 16:33:09 +00002789 // If the division is exact, X % Y is zero.
2790 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2791 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00002792 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00002793 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00002794 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00002795 }
2796
Chris Lattner74381062009-08-30 07:44:24 +00002797 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00002798 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00002799 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002800 else
Chris Lattner74381062009-08-30 07:44:24 +00002801 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002802 Rem->takeName(BO);
2803
Chris Lattnera2498472009-10-11 21:36:10 +00002804 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00002805 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00002806 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002807 }
2808 }
2809
Chris Lattner8af304a2009-10-11 07:53:15 +00002810 /// i1 mul -> i1 and.
Owen Anderson1d0be152009-08-13 21:58:54 +00002811 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattnera2498472009-10-11 21:36:10 +00002812 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002813
Chris Lattner8af304a2009-10-11 07:53:15 +00002814 // X*(1 << Y) --> X << Y
2815 // (1 << Y)*X --> X << Y
2816 {
2817 Value *Y;
2818 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00002819 return BinaryOperator::CreateShl(Op1, Y);
2820 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00002821 return BinaryOperator::CreateShl(Op0, Y);
2822 }
2823
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002824 // If one of the operands of the multiply is a cast from a boolean value, then
2825 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00002826 // X * Y (where Y is 0 or 1) -> X & (0-Y)
2827 if (!isa<VectorType>(I.getType())) {
2828 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00002829 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00002830
Chris Lattnerd2c58362009-10-11 21:29:45 +00002831 Value *BoolCast = 0, *OtherOp = 0;
2832 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00002833 BoolCast = Op0, OtherOp = Op1;
2834 else if (MaskedValueIsZero(Op1, Negative2))
2835 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00002836
Chris Lattner0036e3a2009-10-11 21:22:21 +00002837 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00002838 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
2839 BoolCast, "tmp");
2840 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002841 }
2842 }
2843
Chris Lattner7e708292002-06-25 16:13:24 +00002844 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002845}
2846
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002847Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2848 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002849 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002850
2851 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00002852 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2853 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002854 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2855 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2856 if (Op1F->isExactlyValue(1.0))
2857 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00002858 } else if (isa<VectorType>(Op1C->getType())) {
2859 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002860 // As above, vector X*splat(1.0) -> X in all defined cases.
2861 if (Constant *Splat = Op1V->getSplatValue()) {
2862 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2863 if (F->isExactlyValue(1.0))
2864 return ReplaceInstUsesWith(I, Op0);
2865 }
2866 }
2867 }
2868
2869 // Try to fold constant mul into select arguments.
2870 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2871 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2872 return R;
2873
2874 if (isa<PHINode>(Op0))
2875 if (Instruction *NV = FoldOpIntoPhi(I))
2876 return NV;
2877 }
2878
Dan Gohman186a6362009-08-12 16:04:34 +00002879 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00002880 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002881 return BinaryOperator::CreateFMul(Op0v, Op1v);
2882
2883 return Changed ? &I : 0;
2884}
2885
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002886/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2887/// instruction.
2888bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2889 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2890
2891 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2892 int NonNullOperand = -1;
2893 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2894 if (ST->isNullValue())
2895 NonNullOperand = 2;
2896 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2897 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2898 if (ST->isNullValue())
2899 NonNullOperand = 1;
2900
2901 if (NonNullOperand == -1)
2902 return false;
2903
2904 Value *SelectCond = SI->getOperand(0);
2905
2906 // Change the div/rem to use 'Y' instead of the select.
2907 I.setOperand(1, SI->getOperand(NonNullOperand));
2908
2909 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2910 // problem. However, the select, or the condition of the select may have
2911 // multiple uses. Based on our knowledge that the operand must be non-zero,
2912 // propagate the known value for the select into other uses of it, and
2913 // propagate a known value of the condition into its other users.
2914
2915 // If the select and condition only have a single use, don't bother with this,
2916 // early exit.
2917 if (SI->use_empty() && SelectCond->hasOneUse())
2918 return true;
2919
2920 // Scan the current block backward, looking for other uses of SI.
2921 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2922
2923 while (BBI != BBFront) {
2924 --BBI;
2925 // If we found a call to a function, we can't assume it will return, so
2926 // information from below it cannot be propagated above it.
2927 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2928 break;
2929
2930 // Replace uses of the select or its condition with the known values.
2931 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2932 I != E; ++I) {
2933 if (*I == SI) {
2934 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002935 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002936 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002937 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2938 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002939 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002940 }
2941 }
2942
2943 // If we past the instruction, quit looking for it.
2944 if (&*BBI == SI)
2945 SI = 0;
2946 if (&*BBI == SelectCond)
2947 SelectCond = 0;
2948
2949 // If we ran out of things to eliminate, break out of the loop.
2950 if (SelectCond == 0 && SI == 0)
2951 break;
2952
2953 }
2954 return true;
2955}
2956
2957
Reid Spencer1628cec2006-10-26 06:15:43 +00002958/// This function implements the transforms on div instructions that work
2959/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2960/// used by the visitors to those instructions.
2961/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002962Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002963 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002964
Chris Lattner50b2ca42008-02-19 06:12:18 +00002965 // undef / X -> 0 for integer.
2966 // undef / X -> undef for FP (the undef could be a snan).
2967 if (isa<UndefValue>(Op0)) {
2968 if (Op0->getType()->isFPOrFPVector())
2969 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002970 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002971 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002972
2973 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002974 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002975 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002976
Reid Spencer1628cec2006-10-26 06:15:43 +00002977 return 0;
2978}
Misha Brukmanfd939082005-04-21 23:48:37 +00002979
Reid Spencer1628cec2006-10-26 06:15:43 +00002980/// This function implements the transforms common to both integer division
2981/// instructions (udiv and sdiv). It is called by the visitors to those integer
2982/// division instructions.
2983/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002984Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002985 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2986
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002987 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002988 if (Op0 == Op1) {
2989 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002990 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002991 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00002992 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002993 }
2994
Owen Andersoneed707b2009-07-24 23:12:02 +00002995 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002996 return ReplaceInstUsesWith(I, CI);
2997 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002998
Reid Spencer1628cec2006-10-26 06:15:43 +00002999 if (Instruction *Common = commonDivTransforms(I))
3000 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003001
3002 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3003 // This does not apply for fdiv.
3004 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3005 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00003006
3007 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3008 // div X, 1 == X
3009 if (RHS->equalsInt(1))
3010 return ReplaceInstUsesWith(I, Op0);
3011
3012 // (X / C1) / C2 -> X / (C1*C2)
3013 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3014 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3015 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003016 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00003017 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00003018 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003019 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003020 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003021 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003022 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003023
Reid Spencerbca0e382007-03-23 20:05:17 +00003024 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003025 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3026 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3027 return R;
3028 if (isa<PHINode>(Op0))
3029 if (Instruction *NV = FoldOpIntoPhi(I))
3030 return NV;
3031 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003032 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003033
Chris Lattnera2881962003-02-18 19:28:33 +00003034 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003035 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003036 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003037 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003038
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003039 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003040 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003041 return ReplaceInstUsesWith(I, Op0);
3042
Nick Lewycky895f0852008-11-27 20:21:08 +00003043 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3044 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3045 // div X, 1 == X
3046 if (X->isOne())
3047 return ReplaceInstUsesWith(I, Op0);
3048 }
3049
Reid Spencer1628cec2006-10-26 06:15:43 +00003050 return 0;
3051}
3052
3053Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3054 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3055
3056 // Handle the integer div common cases
3057 if (Instruction *Common = commonIDivTransforms(I))
3058 return Common;
3059
Reid Spencer1628cec2006-10-26 06:15:43 +00003060 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003061 // X udiv C^2 -> X >> C
3062 // Check to see if this is an unsigned division with an exact power of 2,
3063 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003064 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003065 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003066 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003067
3068 // X udiv C, where C >= signbit
3069 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003070 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003071 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003072 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003073 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003074 }
3075
3076 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003077 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003078 if (RHSI->getOpcode() == Instruction::Shl &&
3079 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003080 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003081 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003082 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003083 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003084 if (uint32_t C2 = C1.logBase2())
3085 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003086 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003087 }
3088 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003089 }
3090
Reid Spencer1628cec2006-10-26 06:15:43 +00003091 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3092 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003093 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003094 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003095 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003096 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003097 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003098 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003099 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003100 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003101 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003102 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003103
3104 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003105 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003106 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003107
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003108 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003109 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003110 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003111 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003112 return 0;
3113}
3114
Reid Spencer1628cec2006-10-26 06:15:43 +00003115Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3116 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3117
3118 // Handle the integer div common cases
3119 if (Instruction *Common = commonIDivTransforms(I))
3120 return Common;
3121
3122 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3123 // sdiv X, -1 == -X
3124 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003125 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003126
Dan Gohmanfa94b942009-08-12 16:33:09 +00003127 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003128 if (cast<SDivOperator>(&I)->isExact() &&
3129 RHS->getValue().isNonNegative() &&
3130 RHS->getValue().isPowerOf2()) {
3131 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3132 RHS->getValue().exactLogBase2());
3133 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3134 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003135
3136 // -X/C --> X/-C provided the negation doesn't overflow.
3137 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3138 if (isa<Constant>(Sub->getOperand(0)) &&
3139 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003140 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003141 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3142 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003143 }
3144
3145 // If the sign bits of both operands are zero (i.e. we can prove they are
3146 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003147 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003148 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003149 if (MaskedValueIsZero(Op0, Mask)) {
3150 if (MaskedValueIsZero(Op1, Mask)) {
3151 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3152 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3153 }
3154 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003155 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003156 ShiftedInt->getValue().isPowerOf2()) {
3157 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3158 // Safe because the only negative value (1 << Y) can take on is
3159 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3160 // the sign bit set.
3161 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3162 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003163 }
Eli Friedman8be17392009-07-18 09:53:21 +00003164 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003165
3166 return 0;
3167}
3168
3169Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3170 return commonDivTransforms(I);
3171}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003172
Reid Spencer0a783f72006-11-02 01:53:59 +00003173/// This function implements the transforms on rem instructions that work
3174/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3175/// is used by the visitors to those instructions.
3176/// @brief Transforms common to all three rem instructions
3177Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003178 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003179
Chris Lattner50b2ca42008-02-19 06:12:18 +00003180 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3181 if (I.getType()->isFPOrFPVector())
3182 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003183 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003184 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003185 if (isa<UndefValue>(Op1))
3186 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003187
3188 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003189 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3190 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003191
Reid Spencer0a783f72006-11-02 01:53:59 +00003192 return 0;
3193}
3194
3195/// This function implements the transforms common to both integer remainder
3196/// instructions (urem and srem). It is called by the visitors to those integer
3197/// remainder instructions.
3198/// @brief Common integer remainder transforms
3199Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3200 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3201
3202 if (Instruction *common = commonRemTransforms(I))
3203 return common;
3204
Dale Johannesened6af242009-01-21 00:35:19 +00003205 // 0 % X == 0 for integer, we don't need to preserve faults!
3206 if (Constant *LHS = dyn_cast<Constant>(Op0))
3207 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003208 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003209
Chris Lattner857e8cd2004-12-12 21:48:58 +00003210 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003211 // X % 0 == undef, we don't need to preserve faults!
3212 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003213 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003214
Chris Lattnera2881962003-02-18 19:28:33 +00003215 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003216 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003217
Chris Lattner97943922006-02-28 05:49:21 +00003218 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3219 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3220 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3221 return R;
3222 } else if (isa<PHINode>(Op0I)) {
3223 if (Instruction *NV = FoldOpIntoPhi(I))
3224 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003225 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003226
3227 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003228 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003229 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003230 }
Chris Lattnera2881962003-02-18 19:28:33 +00003231 }
3232
Reid Spencer0a783f72006-11-02 01:53:59 +00003233 return 0;
3234}
3235
3236Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3237 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3238
3239 if (Instruction *common = commonIRemTransforms(I))
3240 return common;
3241
3242 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3243 // X urem C^2 -> X and C
3244 // Check to see if this is an unsigned remainder with an exact power of 2,
3245 // if so, convert to a bitwise and.
3246 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003247 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003248 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003249 }
3250
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003251 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003252 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3253 if (RHSI->getOpcode() == Instruction::Shl &&
3254 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003255 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003256 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003257 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003258 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003259 }
3260 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003261 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003262
Reid Spencer0a783f72006-11-02 01:53:59 +00003263 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3264 // where C1&C2 are powers of two.
3265 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3266 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3267 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3268 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003269 if ((STO->getValue().isPowerOf2()) &&
3270 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003271 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3272 SI->getName()+".t");
3273 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3274 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003275 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003276 }
3277 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003278 }
3279
Chris Lattner3f5b8772002-05-06 16:14:14 +00003280 return 0;
3281}
3282
Reid Spencer0a783f72006-11-02 01:53:59 +00003283Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3284 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3285
Dan Gohmancff55092007-11-05 23:16:33 +00003286 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003287 if (Instruction *Common = commonIRemTransforms(I))
3288 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003289
Dan Gohman186a6362009-08-12 16:04:34 +00003290 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003291 if (!isa<Constant>(RHSNeg) ||
3292 (isa<ConstantInt>(RHSNeg) &&
3293 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003294 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003295 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003296 I.setOperand(1, RHSNeg);
3297 return &I;
3298 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003299
Dan Gohmancff55092007-11-05 23:16:33 +00003300 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003301 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003302 if (I.getType()->isInteger()) {
3303 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3304 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3305 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003306 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003307 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003308 }
3309
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003310 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003311 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3312 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003313
Nick Lewycky9dce8732008-12-20 16:48:00 +00003314 bool hasNegative = false;
3315 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3316 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3317 if (RHS->getValue().isNegative())
3318 hasNegative = true;
3319
3320 if (hasNegative) {
3321 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003322 for (unsigned i = 0; i != VWidth; ++i) {
3323 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3324 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003325 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003326 else
3327 Elts[i] = RHS;
3328 }
3329 }
3330
Owen Andersonaf7ec972009-07-28 21:19:26 +00003331 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003332 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003333 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003334 I.setOperand(1, NewRHSV);
3335 return &I;
3336 }
3337 }
3338 }
3339
Reid Spencer0a783f72006-11-02 01:53:59 +00003340 return 0;
3341}
3342
3343Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003344 return commonRemTransforms(I);
3345}
3346
Chris Lattner457dd822004-06-09 07:59:58 +00003347// isOneBitSet - Return true if there is exactly one bit set in the specified
3348// constant.
3349static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003350 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003351}
3352
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003353// isHighOnes - Return true if the constant is of the form 1+0+.
3354// This is the same as lowones(~X).
3355static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003356 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003357}
3358
Reid Spencere4d87aa2006-12-23 06:05:41 +00003359/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003360/// are carefully arranged to allow folding of expressions such as:
3361///
3362/// (A < B) | (A > B) --> (A != B)
3363///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003364/// Note that this is only valid if the first and second predicates have the
3365/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003366///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003367/// Three bits are used to represent the condition, as follows:
3368/// 0 A > B
3369/// 1 A == B
3370/// 2 A < B
3371///
3372/// <=> Value Definition
3373/// 000 0 Always false
3374/// 001 1 A > B
3375/// 010 2 A == B
3376/// 011 3 A >= B
3377/// 100 4 A < B
3378/// 101 5 A != B
3379/// 110 6 A <= B
3380/// 111 7 Always true
3381///
3382static unsigned getICmpCode(const ICmpInst *ICI) {
3383 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003384 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003385 case ICmpInst::ICMP_UGT: return 1; // 001
3386 case ICmpInst::ICMP_SGT: return 1; // 001
3387 case ICmpInst::ICMP_EQ: return 2; // 010
3388 case ICmpInst::ICMP_UGE: return 3; // 011
3389 case ICmpInst::ICMP_SGE: return 3; // 011
3390 case ICmpInst::ICMP_ULT: return 4; // 100
3391 case ICmpInst::ICMP_SLT: return 4; // 100
3392 case ICmpInst::ICMP_NE: return 5; // 101
3393 case ICmpInst::ICMP_ULE: return 6; // 110
3394 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003395 // True -> 7
3396 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003397 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003398 return 0;
3399 }
3400}
3401
Evan Cheng8db90722008-10-14 17:15:11 +00003402/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3403/// predicate into a three bit mask. It also returns whether it is an ordered
3404/// predicate by reference.
3405static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3406 isOrdered = false;
3407 switch (CC) {
3408 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3409 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003410 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3411 case FCmpInst::FCMP_UGT: return 1; // 001
3412 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3413 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003414 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3415 case FCmpInst::FCMP_UGE: return 3; // 011
3416 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3417 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003418 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3419 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003420 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3421 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003422 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003423 default:
3424 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003425 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003426 return 0;
3427 }
3428}
3429
Reid Spencere4d87aa2006-12-23 06:05:41 +00003430/// getICmpValue - This is the complement of getICmpCode, which turns an
3431/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003432/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003433/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003434static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003435 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003436 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003437 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003438 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003439 case 1:
3440 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003441 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003442 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003443 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3444 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003445 case 3:
3446 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003447 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003448 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003449 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003450 case 4:
3451 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003452 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003453 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003454 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3455 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003456 case 6:
3457 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003458 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003459 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003460 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003461 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003462 }
3463}
3464
Evan Cheng8db90722008-10-14 17:15:11 +00003465/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3466/// opcode and two operands into either a FCmp instruction. isordered is passed
3467/// in to determine which kind of predicate to use in the new fcmp instruction.
3468static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003469 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003470 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003471 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003472 case 0:
3473 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003474 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003475 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003476 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003477 case 1:
3478 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003479 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003480 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003481 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003482 case 2:
3483 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003484 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003485 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003486 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003487 case 3:
3488 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003489 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003490 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003491 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003492 case 4:
3493 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003494 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003495 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003496 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003497 case 5:
3498 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003499 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003500 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003501 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003502 case 6:
3503 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003504 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003505 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003506 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003507 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003508 }
3509}
3510
Chris Lattnerb9553d62008-11-16 04:55:20 +00003511/// PredicatesFoldable - Return true if both predicates match sign or if at
3512/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003513static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00003514 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3515 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3516 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003517}
3518
3519namespace {
3520// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3521struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003522 InstCombiner &IC;
3523 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003524 ICmpInst::Predicate pred;
3525 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3526 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3527 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003528 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003529 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3530 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003531 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3532 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003533 return false;
3534 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003535 Instruction *apply(Instruction &Log) const {
3536 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3537 if (ICI->getOperand(0) != LHS) {
3538 assert(ICI->getOperand(1) == LHS);
3539 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003540 }
3541
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003542 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003543 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003544 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003545 unsigned Code;
3546 switch (Log.getOpcode()) {
3547 case Instruction::And: Code = LHSCode & RHSCode; break;
3548 case Instruction::Or: Code = LHSCode | RHSCode; break;
3549 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003550 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003551 }
3552
Nick Lewycky4a134af2009-10-25 05:20:17 +00003553 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Andersond672ecb2009-07-03 00:17:18 +00003554 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003555 if (Instruction *I = dyn_cast<Instruction>(RV))
3556 return I;
3557 // Otherwise, it's a constant boolean value...
3558 return IC.ReplaceInstUsesWith(Log, RV);
3559 }
3560};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003561} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003562
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003563// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3564// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003565// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003566Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003567 ConstantInt *OpRHS,
3568 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003569 BinaryOperator &TheAnd) {
3570 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003571 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003572 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003573 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003574
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003575 switch (Op->getOpcode()) {
3576 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003577 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003578 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003579 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003580 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003581 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003582 }
3583 break;
3584 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003585 if (Together == AndRHS) // (X | C) & C --> C
3586 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003587
Chris Lattner6e7ba452005-01-01 16:22:27 +00003588 if (Op->hasOneUse() && Together != OpRHS) {
3589 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003590 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003591 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003592 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003593 }
3594 break;
3595 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003596 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003597 // Adding a one to a single bit bit-field should be turned into an XOR
3598 // of the bit. First thing to check is to see if this AND is with a
3599 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003600 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003601
3602 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003603 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003604 // Ok, at this point, we know that we are masking the result of the
3605 // ADD down to exactly one bit. If the constant we are adding has
3606 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003607 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003608
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003609 // Check to see if any bits below the one bit set in AndRHSV are set.
3610 if ((AddRHS & (AndRHSV-1)) == 0) {
3611 // If not, the only thing that can effect the output of the AND is
3612 // the bit specified by AndRHSV. If that bit is set, the effect of
3613 // the XOR is to toggle the bit. If it is clear, then the ADD has
3614 // no effect.
3615 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3616 TheAnd.setOperand(0, X);
3617 return &TheAnd;
3618 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003619 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003620 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003621 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003622 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003623 }
3624 }
3625 }
3626 }
3627 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003628
3629 case Instruction::Shl: {
3630 // We know that the AND will not produce any of the bits shifted in, so if
3631 // the anded constant includes them, clear them now!
3632 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003633 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003634 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003635 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003636 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003637
Zhou Sheng290bec52007-03-29 08:15:12 +00003638 if (CI->getValue() == ShlMask) {
3639 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003640 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3641 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003642 TheAnd.setOperand(1, CI);
3643 return &TheAnd;
3644 }
3645 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003646 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003647 case Instruction::LShr:
3648 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003649 // We know that the AND will not produce any of the bits shifted in, so if
3650 // the anded constant includes them, clear them now! This only applies to
3651 // unsigned shifts, because a signed shr may bring in set bits!
3652 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003653 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003654 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003655 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003656 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003657
Zhou Sheng290bec52007-03-29 08:15:12 +00003658 if (CI->getValue() == ShrMask) {
3659 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003660 return ReplaceInstUsesWith(TheAnd, Op);
3661 } else if (CI != AndRHS) {
3662 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3663 return &TheAnd;
3664 }
3665 break;
3666 }
3667 case Instruction::AShr:
3668 // Signed shr.
3669 // See if this is shifting in some sign extension, then masking it out
3670 // with an and.
3671 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003672 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003673 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003674 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003675 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003676 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003677 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003678 // Make the argument unsigned.
3679 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003680 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003681 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003682 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003683 }
3684 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003685 }
3686 return 0;
3687}
3688
Chris Lattner8b170942002-08-09 23:47:40 +00003689
Chris Lattnera96879a2004-09-29 17:40:11 +00003690/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3691/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003692/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3693/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003694/// insert new instructions.
3695Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003696 bool isSigned, bool Inside,
3697 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003698 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003699 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003700 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003701
Chris Lattnera96879a2004-09-29 17:40:11 +00003702 if (Inside) {
3703 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003704 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003705
Reid Spencere4d87aa2006-12-23 06:05:41 +00003706 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003707 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003708 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003709 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003710 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003711 }
3712
3713 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003714 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003715 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003716 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003717 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003718 }
3719
3720 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003721 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003722
Reid Spencere4e40032007-03-21 23:19:50 +00003723 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003724 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003725 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003726 ICmpInst::Predicate pred = (isSigned ?
3727 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003728 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003729 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003730
Reid Spencere4e40032007-03-21 23:19:50 +00003731 // Emit V-Lo >u Hi-1-Lo
3732 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003733 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003734 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003735 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003736 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003737}
3738
Chris Lattner7203e152005-09-18 07:22:02 +00003739// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3740// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3741// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3742// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003743static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003744 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003745 uint32_t BitWidth = Val->getType()->getBitWidth();
3746 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003747
3748 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003749 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003750 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003751 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003752 return true;
3753}
3754
Chris Lattner7203e152005-09-18 07:22:02 +00003755/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3756/// where isSub determines whether the operator is a sub. If we can fold one of
3757/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003758///
3759/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3760/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3761/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3762///
3763/// return (A +/- B).
3764///
3765Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003766 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003767 Instruction &I) {
3768 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3769 if (!LHSI || LHSI->getNumOperands() != 2 ||
3770 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3771
3772 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3773
3774 switch (LHSI->getOpcode()) {
3775 default: return 0;
3776 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003777 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003778 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003779 if ((Mask->getValue().countLeadingZeros() +
3780 Mask->getValue().countPopulation()) ==
3781 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003782 break;
3783
3784 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3785 // part, we don't need any explicit masks to take them out of A. If that
3786 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003787 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003788 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003789 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003790 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003791 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003792 break;
3793 }
3794 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003795 return 0;
3796 case Instruction::Or:
3797 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003798 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003799 if ((Mask->getValue().countLeadingZeros() +
3800 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003801 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003802 break;
3803 return 0;
3804 }
3805
Chris Lattnerc8e77562005-09-18 04:24:45 +00003806 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00003807 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3808 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003809}
3810
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003811/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3812Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3813 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003814 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003815 ConstantInt *LHSCst, *RHSCst;
3816 ICmpInst::Predicate LHSCC, RHSCC;
3817
Chris Lattnerea065fb2008-11-16 05:10:52 +00003818 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003819 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003820 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003821 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003822 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003823 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003824
3825 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3826 // where C is a power of 2
3827 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3828 LHSCst->getValue().isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00003829 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003830 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003831 }
3832
3833 // From here on, we only handle:
3834 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3835 if (Val != Val2) return 0;
3836
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003837 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3838 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3839 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3840 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3841 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3842 return 0;
3843
3844 // We can't fold (ugt x, C) & (sgt x, C2).
3845 if (!PredicatesFoldable(LHSCC, RHSCC))
3846 return 0;
3847
3848 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003849 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00003850 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003851 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00003852 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003853 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003854 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003855 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3856
3857 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003858 std::swap(LHS, RHS);
3859 std::swap(LHSCst, RHSCst);
3860 std::swap(LHSCC, RHSCC);
3861 }
3862
3863 // At this point, we know we have have two icmp instructions
3864 // comparing a value against two constants and and'ing the result
3865 // together. Because of the above check, we know that we only have
3866 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3867 // (from the FoldICmpLogical check above), that the two constants
3868 // are not equal and that the larger constant is on the RHS
3869 assert(LHSCst != RHSCst && "Compares not folded above?");
3870
3871 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003872 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003873 case ICmpInst::ICMP_EQ:
3874 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003875 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003876 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3877 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3878 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003879 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003880 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3881 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3882 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3883 return ReplaceInstUsesWith(I, LHS);
3884 }
3885 case ICmpInst::ICMP_NE:
3886 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003887 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003888 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003889 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003890 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003891 break; // (X != 13 & X u< 15) -> no change
3892 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003893 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003894 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003895 break; // (X != 13 & X s< 15) -> no change
3896 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3897 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3898 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3899 return ReplaceInstUsesWith(I, RHS);
3900 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003901 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003902 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00003903 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003904 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003905 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003906 }
3907 break; // (X != 13 & X != 15) -> no change
3908 }
3909 break;
3910 case ICmpInst::ICMP_ULT:
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) -> false
3914 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003915 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003916 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3917 break;
3918 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3919 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3920 return ReplaceInstUsesWith(I, LHS);
3921 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3922 break;
3923 }
3924 break;
3925 case ICmpInst::ICMP_SLT:
3926 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003927 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003928 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3929 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003930 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003931 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3932 break;
3933 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3934 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3935 return ReplaceInstUsesWith(I, LHS);
3936 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3937 break;
3938 }
3939 break;
3940 case ICmpInst::ICMP_UGT:
3941 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003942 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003943 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3944 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3945 return ReplaceInstUsesWith(I, RHS);
3946 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3947 break;
3948 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003949 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003950 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003951 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003952 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003953 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003954 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003955 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3956 break;
3957 }
3958 break;
3959 case ICmpInst::ICMP_SGT:
3960 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003961 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003962 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3963 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3964 return ReplaceInstUsesWith(I, RHS);
3965 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3966 break;
3967 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003968 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003969 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003970 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003971 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003972 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003973 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003974 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3975 break;
3976 }
3977 break;
3978 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003979
3980 return 0;
3981}
3982
Chris Lattner42d1be02009-07-23 05:14:02 +00003983Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3984 FCmpInst *RHS) {
3985
3986 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3987 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3988 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3989 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3990 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3991 // If either of the constants are nans, then the whole thing returns
3992 // false.
3993 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00003994 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003995 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00003996 LHS->getOperand(0), RHS->getOperand(0));
3997 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003998
3999 // Handle vector zeros. This occurs because the canonical form of
4000 // "fcmp ord x,x" is "fcmp ord x, 0".
4001 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4002 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004003 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00004004 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00004005 return 0;
4006 }
4007
4008 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4009 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4010 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4011
4012
4013 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4014 // Swap RHS operands to match LHS.
4015 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4016 std::swap(Op1LHS, Op1RHS);
4017 }
4018
4019 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4020 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4021 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004022 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004023
4024 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004025 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004026 if (Op0CC == FCmpInst::FCMP_TRUE)
4027 return ReplaceInstUsesWith(I, RHS);
4028 if (Op1CC == FCmpInst::FCMP_TRUE)
4029 return ReplaceInstUsesWith(I, LHS);
4030
4031 bool Op0Ordered;
4032 bool Op1Ordered;
4033 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4034 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4035 if (Op1Pred == 0) {
4036 std::swap(LHS, RHS);
4037 std::swap(Op0Pred, Op1Pred);
4038 std::swap(Op0Ordered, Op1Ordered);
4039 }
4040 if (Op0Pred == 0) {
4041 // uno && ueq -> uno && (uno || eq) -> ueq
4042 // ord && olt -> ord && (ord && lt) -> olt
4043 if (Op0Ordered == Op1Ordered)
4044 return ReplaceInstUsesWith(I, RHS);
4045
4046 // uno && oeq -> uno && (ord && eq) -> false
4047 // uno && ord -> false
4048 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004049 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004050 // ord && ueq -> ord && (uno || eq) -> oeq
4051 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4052 Op0LHS, Op0RHS, Context));
4053 }
4054 }
4055
4056 return 0;
4057}
4058
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004059
Chris Lattner7e708292002-06-25 16:13:24 +00004060Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004061 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004062 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004063
Chris Lattnere87597f2004-10-16 18:11:37 +00004064 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004065 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004066
Chris Lattner6e7ba452005-01-01 16:22:27 +00004067 // and X, X = X
4068 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004069 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004070
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004071 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004072 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004073 if (SimplifyDemandedInstructionBits(I))
4074 return &I;
4075 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004076 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004077 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004078 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004079 } else if (isa<ConstantAggregateZero>(Op1)) {
4080 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004081 }
4082 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004083
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004084 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004085 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004086 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004087
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004088 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004089 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00004090 Value *Op0LHS = Op0I->getOperand(0);
4091 Value *Op0RHS = Op0I->getOperand(1);
4092 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004093 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004094 case Instruction::Xor:
4095 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004096 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004097 if (!Op0I->hasOneUse()) break;
4098
4099 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4100 // Not masking anything out for the LHS, move to RHS.
4101 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4102 Op0RHS->getName()+".masked");
4103 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4104 }
4105 if (!isa<Constant>(Op0RHS) &&
4106 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4107 // Not masking anything out for the RHS, move to LHS.
4108 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4109 Op0LHS->getName()+".masked");
4110 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00004111 }
4112
Chris Lattner6e7ba452005-01-01 16:22:27 +00004113 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004114 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004115 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4116 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4117 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4118 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004119 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004120 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004121 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004122 break;
4123
4124 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004125 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4126 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4127 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4128 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004129 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004130
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004131 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4132 // has 1's for all bits that the subtraction with A might affect.
4133 if (Op0I->hasOneUse()) {
4134 uint32_t BitWidth = AndRHSMask.getBitWidth();
4135 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4136 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4137
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004138 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004139 if (!(A && A->isZero()) && // avoid infinite recursion.
4140 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004141 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004142 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4143 }
4144 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004145 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004146
4147 case Instruction::Shl:
4148 case Instruction::LShr:
4149 // (1 << x) & 1 --> zext(x == 0)
4150 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004151 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004152 Value *NewICmp =
4153 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004154 return new ZExtInst(NewICmp, I.getType());
4155 }
4156 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004157 }
4158
Chris Lattner58403262003-07-23 19:25:52 +00004159 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004160 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004161 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004162 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004163 // If this is an integer truncation or change from signed-to-unsigned, and
4164 // if the source is an and/or with immediate, transform it. This
4165 // frequently occurs for bitfield accesses.
4166 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004167 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004168 CastOp->getNumOperands() == 2)
Evan Cheng85def162009-10-26 03:51:32 +00004169 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004170 if (CastOp->getOpcode() == Instruction::And) {
4171 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004172 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4173 // This will fold the two constants together, which may allow
4174 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004175 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004176 CastOp->getOperand(0), I.getType(),
4177 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004178 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004179 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004180 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004181 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004182 } else if (CastOp->getOpcode() == Instruction::Or) {
4183 // Change: and (cast (or X, C1) to T), C2
4184 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004185 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004186 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004187 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004188 return ReplaceInstUsesWith(I, AndRHS);
4189 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004190 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004191 }
Chris Lattner06782f82003-07-23 19:36:21 +00004192 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004193
4194 // Try to fold constant and into select arguments.
4195 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004196 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004197 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004198 if (isa<PHINode>(Op0))
4199 if (Instruction *NV = FoldOpIntoPhi(I))
4200 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004201 }
4202
Dan Gohman186a6362009-08-12 16:04:34 +00004203 Value *Op0NotVal = dyn_castNotVal(Op0);
4204 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004205
Chris Lattner5b62aa72004-06-18 06:07:51 +00004206 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004207 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004208
Misha Brukmancb6267b2004-07-30 12:50:08 +00004209 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004210 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004211 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4212 I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004213 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004214 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004215
4216 {
Chris Lattner003b6202007-06-15 05:58:24 +00004217 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004218 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004219 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4220 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004221
4222 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004223 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004224 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004225 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004226 }
4227 }
4228
Dan Gohman4ae51262009-08-12 16:23:25 +00004229 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004230 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4231 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004232
4233 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004234 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004235 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004236 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004237 }
4238 }
Chris Lattner64daab52006-04-01 08:03:55 +00004239
4240 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004241 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004242 if (A == Op1) { // (A^B)&A -> A&(A^B)
4243 I.swapOperands(); // Simplify below
4244 std::swap(Op0, Op1);
4245 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4246 cast<BinaryOperator>(Op0)->swapOperands();
4247 I.swapOperands(); // Simplify below
4248 std::swap(Op0, Op1);
4249 }
4250 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004251
Chris Lattner64daab52006-04-01 08:03:55 +00004252 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004253 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004254 if (B == Op0) { // B&(A^B) -> B&(B^A)
4255 cast<BinaryOperator>(Op1)->swapOperands();
4256 std::swap(A, B);
4257 }
Chris Lattner74381062009-08-30 07:44:24 +00004258 if (A == Op0) // A&(A^B) -> A & ~B
4259 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004260 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004261
4262 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004263 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4264 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004265 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004266 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4267 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004268 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004269 }
4270
Reid Spencere4d87aa2006-12-23 06:05:41 +00004271 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4272 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004273 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004274 return R;
4275
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004276 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4277 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4278 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004279 }
4280
Chris Lattner6fc205f2006-05-05 06:39:07 +00004281 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004282 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4283 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4284 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4285 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004286 if (SrcTy == Op1C->getOperand(0)->getType() &&
4287 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004288 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004289 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4290 I.getType(), TD) &&
4291 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4292 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004293 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4294 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004295 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004296 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004297 }
Chris Lattnere511b742006-11-14 07:46:50 +00004298
4299 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004300 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4301 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4302 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004303 SI0->getOperand(1) == SI1->getOperand(1) &&
4304 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004305 Value *NewOp =
4306 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4307 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004308 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004309 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004310 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004311 }
4312
Evan Cheng8db90722008-10-14 17:15:11 +00004313 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004314 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004315 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4316 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4317 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004318 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004319
Chris Lattner7e708292002-06-25 16:13:24 +00004320 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004321}
4322
Chris Lattner8c34cd22008-10-05 02:13:19 +00004323/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4324/// capable of providing pieces of a bswap. The subexpression provides pieces
4325/// of a bswap if it is proven that each of the non-zero bytes in the output of
4326/// the expression came from the corresponding "byte swapped" byte in some other
4327/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4328/// we know that the expression deposits the low byte of %X into the high byte
4329/// of the bswap result and that all other bytes are zero. This expression is
4330/// accepted, the high byte of ByteValues is set to X to indicate a correct
4331/// match.
4332///
4333/// This function returns true if the match was unsuccessful and false if so.
4334/// On entry to the function the "OverallLeftShift" is a signed integer value
4335/// indicating the number of bytes that the subexpression is later shifted. For
4336/// example, if the expression is later right shifted by 16 bits, the
4337/// OverallLeftShift value would be -2 on entry. This is used to specify which
4338/// byte of ByteValues is actually being set.
4339///
4340/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4341/// byte is masked to zero by a user. For example, in (X & 255), X will be
4342/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4343/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4344/// always in the local (OverallLeftShift) coordinate space.
4345///
4346static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4347 SmallVector<Value*, 8> &ByteValues) {
4348 if (Instruction *I = dyn_cast<Instruction>(V)) {
4349 // If this is an or instruction, it may be an inner node of the bswap.
4350 if (I->getOpcode() == Instruction::Or) {
4351 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4352 ByteValues) ||
4353 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4354 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004355 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004356
4357 // If this is a logical shift by a constant multiple of 8, recurse with
4358 // OverallLeftShift and ByteMask adjusted.
4359 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4360 unsigned ShAmt =
4361 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4362 // Ensure the shift amount is defined and of a byte value.
4363 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4364 return true;
4365
4366 unsigned ByteShift = ShAmt >> 3;
4367 if (I->getOpcode() == Instruction::Shl) {
4368 // X << 2 -> collect(X, +2)
4369 OverallLeftShift += ByteShift;
4370 ByteMask >>= ByteShift;
4371 } else {
4372 // X >>u 2 -> collect(X, -2)
4373 OverallLeftShift -= ByteShift;
4374 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004375 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004376 }
4377
4378 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4379 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4380
4381 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4382 ByteValues);
4383 }
4384
4385 // If this is a logical 'and' with a mask that clears bytes, clear the
4386 // corresponding bytes in ByteMask.
4387 if (I->getOpcode() == Instruction::And &&
4388 isa<ConstantInt>(I->getOperand(1))) {
4389 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4390 unsigned NumBytes = ByteValues.size();
4391 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4392 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4393
4394 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4395 // If this byte is masked out by a later operation, we don't care what
4396 // the and mask is.
4397 if ((ByteMask & (1 << i)) == 0)
4398 continue;
4399
4400 // If the AndMask is all zeros for this byte, clear the bit.
4401 APInt MaskB = AndMask & Byte;
4402 if (MaskB == 0) {
4403 ByteMask &= ~(1U << i);
4404 continue;
4405 }
4406
4407 // If the AndMask is not all ones for this byte, it's not a bytezap.
4408 if (MaskB != Byte)
4409 return true;
4410
4411 // Otherwise, this byte is kept.
4412 }
4413
4414 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4415 ByteValues);
4416 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004417 }
4418
Chris Lattner8c34cd22008-10-05 02:13:19 +00004419 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4420 // the input value to the bswap. Some observations: 1) if more than one byte
4421 // is demanded from this input, then it could not be successfully assembled
4422 // into a byteswap. At least one of the two bytes would not be aligned with
4423 // their ultimate destination.
4424 if (!isPowerOf2_32(ByteMask)) return true;
4425 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004426
Chris Lattner8c34cd22008-10-05 02:13:19 +00004427 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4428 // is demanded, it needs to go into byte 0 of the result. This means that the
4429 // byte needs to be shifted until it lands in the right byte bucket. The
4430 // shift amount depends on the position: if the byte is coming from the high
4431 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4432 // low part, it must be shifted left.
4433 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4434 if (InputByteNo < ByteValues.size()/2) {
4435 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4436 return true;
4437 } else {
4438 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4439 return true;
4440 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004441
4442 // If the destination byte value is already defined, the values are or'd
4443 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004444 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004445 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004446 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004447 return false;
4448}
4449
4450/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4451/// If so, insert the new bswap intrinsic and return it.
4452Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004453 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004454 if (!ITy || ITy->getBitWidth() % 16 ||
4455 // ByteMask only allows up to 32-byte values.
4456 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004457 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004458
4459 /// ByteValues - For each byte of the result, we keep track of which value
4460 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004461 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004462 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004463
4464 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004465 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4466 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004467 return 0;
4468
4469 // Check to see if all of the bytes come from the same value.
4470 Value *V = ByteValues[0];
4471 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4472
4473 // Check to make sure that all of the bytes come from the same value.
4474 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4475 if (ByteValues[i] != V)
4476 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004477 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004478 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004479 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004480 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004481}
4482
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004483/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4484/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4485/// we can simplify this expression to "cond ? C : D or B".
4486static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004487 Value *C, Value *D,
4488 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004489 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004490 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004491 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004492 return 0;
4493
Chris Lattnera6a474d2008-11-16 04:26:55 +00004494 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004495 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004496 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004497 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004498 return SelectInst::Create(Cond, C, B);
4499 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004500 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004501 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004502 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004503 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004504 return 0;
4505}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004506
Chris Lattner69d4ced2008-11-16 05:20:07 +00004507/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4508Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4509 ICmpInst *LHS, ICmpInst *RHS) {
4510 Value *Val, *Val2;
4511 ConstantInt *LHSCst, *RHSCst;
4512 ICmpInst::Predicate LHSCC, RHSCC;
4513
4514 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004515 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004516 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004517 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004518 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004519 return 0;
4520
4521 // From here on, we only handle:
4522 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4523 if (Val != Val2) return 0;
4524
4525 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4526 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4527 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4528 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4529 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4530 return 0;
4531
4532 // We can't fold (ugt x, C) | (sgt x, C2).
4533 if (!PredicatesFoldable(LHSCC, RHSCC))
4534 return 0;
4535
4536 // Ensure that the larger constant is on the RHS.
4537 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004538 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00004539 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004540 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004541 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4542 else
4543 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4544
4545 if (ShouldSwap) {
4546 std::swap(LHS, RHS);
4547 std::swap(LHSCst, RHSCst);
4548 std::swap(LHSCC, RHSCC);
4549 }
4550
4551 // At this point, we know we have have two icmp instructions
4552 // comparing a value against two constants and or'ing the result
4553 // together. Because of the above check, we know that we only have
4554 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4555 // FoldICmpLogical check above), that the two constants are not
4556 // equal.
4557 assert(LHSCst != RHSCst && "Compares not folded above?");
4558
4559 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004560 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004561 case ICmpInst::ICMP_EQ:
4562 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004563 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004564 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004565 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004566 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004567 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004568 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004569 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004570 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004571 }
4572 break; // (X == 13 | X == 15) -> no change
4573 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4574 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4575 break;
4576 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4577 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4578 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4579 return ReplaceInstUsesWith(I, RHS);
4580 }
4581 break;
4582 case ICmpInst::ICMP_NE:
4583 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004584 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004585 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4586 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4587 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4588 return ReplaceInstUsesWith(I, LHS);
4589 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4590 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4591 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004592 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004593 }
4594 break;
4595 case ICmpInst::ICMP_ULT:
4596 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004597 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004598 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4599 break;
4600 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4601 // If RHSCst is [us]MAXINT, it is always false. Not handling
4602 // this can cause overflow.
4603 if (RHSCst->isMaxValue(false))
4604 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004605 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004606 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004607 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4608 break;
4609 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4610 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4611 return ReplaceInstUsesWith(I, RHS);
4612 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4613 break;
4614 }
4615 break;
4616 case ICmpInst::ICMP_SLT:
4617 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004618 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004619 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4620 break;
4621 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4622 // If RHSCst is [us]MAXINT, it is always false. Not handling
4623 // this can cause overflow.
4624 if (RHSCst->isMaxValue(true))
4625 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004626 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004627 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004628 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4629 break;
4630 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4631 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4632 return ReplaceInstUsesWith(I, RHS);
4633 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4634 break;
4635 }
4636 break;
4637 case ICmpInst::ICMP_UGT:
4638 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004639 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004640 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4641 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4642 return ReplaceInstUsesWith(I, LHS);
4643 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4644 break;
4645 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4646 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004647 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004648 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4649 break;
4650 }
4651 break;
4652 case ICmpInst::ICMP_SGT:
4653 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004654 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004655 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4656 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4657 return ReplaceInstUsesWith(I, LHS);
4658 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4659 break;
4660 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4661 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004662 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004663 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4664 break;
4665 }
4666 break;
4667 }
4668 return 0;
4669}
4670
Chris Lattner5414cc52009-07-23 05:46:22 +00004671Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4672 FCmpInst *RHS) {
4673 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4674 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4675 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4676 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4677 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4678 // If either of the constants are nans, then the whole thing returns
4679 // true.
4680 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004681 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004682
4683 // Otherwise, no need to compare the two constants, compare the
4684 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004685 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004686 LHS->getOperand(0), RHS->getOperand(0));
4687 }
4688
4689 // Handle vector zeros. This occurs because the canonical form of
4690 // "fcmp uno x,x" is "fcmp uno x, 0".
4691 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4692 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004693 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004694 LHS->getOperand(0), RHS->getOperand(0));
4695
4696 return 0;
4697 }
4698
4699 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4700 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4701 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4702
4703 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4704 // Swap RHS operands to match LHS.
4705 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4706 std::swap(Op1LHS, Op1RHS);
4707 }
4708 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4709 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4710 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004711 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004712 Op0LHS, Op0RHS);
4713 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004714 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004715 if (Op0CC == FCmpInst::FCMP_FALSE)
4716 return ReplaceInstUsesWith(I, RHS);
4717 if (Op1CC == FCmpInst::FCMP_FALSE)
4718 return ReplaceInstUsesWith(I, LHS);
4719 bool Op0Ordered;
4720 bool Op1Ordered;
4721 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4722 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4723 if (Op0Ordered == Op1Ordered) {
4724 // If both are ordered or unordered, return a new fcmp with
4725 // or'ed predicates.
4726 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4727 Op0LHS, Op0RHS, Context);
4728 if (Instruction *I = dyn_cast<Instruction>(RV))
4729 return I;
4730 // Otherwise, it's a constant boolean value...
4731 return ReplaceInstUsesWith(I, RV);
4732 }
4733 }
4734 return 0;
4735}
4736
Bill Wendlinga698a472008-12-01 08:23:25 +00004737/// FoldOrWithConstants - This helper function folds:
4738///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004739/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004740///
4741/// into:
4742///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004743/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004744///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004745/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004746Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004747 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004748 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4749 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004750
Bill Wendling286a0542008-12-02 06:24:20 +00004751 Value *V1 = 0;
4752 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004753 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004754
Bill Wendling29976b92008-12-02 06:18:11 +00004755 APInt Xor = CI1->getValue() ^ CI2->getValue();
4756 if (!Xor.isAllOnesValue()) return 0;
4757
Bill Wendling286a0542008-12-02 06:24:20 +00004758 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00004759 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004760 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004761 }
4762
4763 return 0;
4764}
4765
Chris Lattner7e708292002-06-25 16:13:24 +00004766Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004767 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004768 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004769
Chris Lattner42593e62007-03-24 23:56:43 +00004770 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004771 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004772
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004773 // or X, X = X
4774 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004775 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004776
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004777 // See if we can simplify any instructions used by the instruction whose sole
4778 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004779 if (SimplifyDemandedInstructionBits(I))
4780 return &I;
4781 if (isa<VectorType>(I.getType())) {
4782 if (isa<ConstantAggregateZero>(Op1)) {
4783 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4784 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4785 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4786 return ReplaceInstUsesWith(I, I.getOperand(1));
4787 }
Chris Lattner42593e62007-03-24 23:56:43 +00004788 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004789
Chris Lattner3f5b8772002-05-06 16:14:14 +00004790 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004791 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004792 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004793 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004794 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004795 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004796 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004797 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004798 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004799 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004800 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004801
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004802 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004803 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004804 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004805 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004806 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004807 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004808 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004809 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004810
4811 // Try to fold constant and into select arguments.
4812 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004813 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004814 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004815 if (isa<PHINode>(Op0))
4816 if (Instruction *NV = FoldOpIntoPhi(I))
4817 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004818 }
4819
Chris Lattner4f637d42006-01-06 17:59:59 +00004820 Value *A = 0, *B = 0;
4821 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004822
Dan Gohman4ae51262009-08-12 16:23:25 +00004823 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004824 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4825 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004826 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004827 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4828 return ReplaceInstUsesWith(I, Op0);
4829
Chris Lattner6423d4c2006-07-10 20:25:24 +00004830 // (A | B) | C and A | (B | C) -> bswap if possible.
4831 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004832 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4833 match(Op1, m_Or(m_Value(), m_Value())) ||
4834 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4835 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004836 if (Instruction *BSwap = MatchBSwap(I))
4837 return BSwap;
4838 }
4839
Chris Lattner6e4c6492005-05-09 04:58:36 +00004840 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004841 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004842 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004843 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004844 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004845 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004846 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004847 }
4848
4849 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004850 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004851 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004852 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004853 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004854 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004855 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004856 }
4857
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004858 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004859 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004860 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4861 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004862 Value *V1 = 0, *V2 = 0, *V3 = 0;
4863 C1 = dyn_cast<ConstantInt>(C);
4864 C2 = dyn_cast<ConstantInt>(D);
4865 if (C1 && C2) { // (A & C1)|(B & C2)
4866 // If we have: ((V + N) & C1) | (V & C2)
4867 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4868 // replace with V+N.
4869 if (C1->getValue() == ~C2->getValue()) {
4870 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004871 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004872 // Add commutes, try both ways.
4873 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4874 return ReplaceInstUsesWith(I, A);
4875 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4876 return ReplaceInstUsesWith(I, A);
4877 }
4878 // Or commutes, try both ways.
4879 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004880 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004881 // Add commutes, try both ways.
4882 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4883 return ReplaceInstUsesWith(I, B);
4884 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4885 return ReplaceInstUsesWith(I, B);
4886 }
4887 }
Chris Lattner044e5332007-04-08 08:01:49 +00004888 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004889 }
4890
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004891 // Check to see if we have any common things being and'ed. If so, find the
4892 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004893 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4894 if (A == B) // (A & C)|(A & D) == A & (C|D)
4895 V1 = A, V2 = C, V3 = D;
4896 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4897 V1 = A, V2 = B, V3 = C;
4898 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4899 V1 = C, V2 = A, V3 = D;
4900 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4901 V1 = C, V2 = A, V3 = B;
4902
4903 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00004904 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004905 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004906 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004907 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004908
Dan Gohman1975d032008-10-30 20:40:10 +00004909 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004910 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004911 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004912 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004913 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004914 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004915 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004916 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004917 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004918
Bill Wendlingb01865c2008-11-30 13:52:49 +00004919 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004920 if ((match(C, m_Not(m_Specific(D))) &&
4921 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004922 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004923 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004924 if ((match(A, m_Not(m_Specific(D))) &&
4925 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004926 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004927 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004928 if ((match(C, m_Not(m_Specific(B))) &&
4929 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004930 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004931 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004932 if ((match(A, m_Not(m_Specific(B))) &&
4933 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004934 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004935 }
Chris Lattnere511b742006-11-14 07:46:50 +00004936
4937 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004938 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4939 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4940 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004941 SI0->getOperand(1) == SI1->getOperand(1) &&
4942 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004943 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4944 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004945 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004946 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004947 }
4948 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004949
Bill Wendlingb3833d12008-12-01 01:07:11 +00004950 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004951 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4952 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004953 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004954 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004955 }
4956 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004957 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4958 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004959 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004960 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004961 }
4962
Dan Gohman4ae51262009-08-12 16:23:25 +00004963 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004964 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004965 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004966 } else {
4967 A = 0;
4968 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004969 // Note, A is still live here!
Dan Gohman4ae51262009-08-12 16:23:25 +00004970 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004971 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004972 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004973
Misha Brukmancb6267b2004-07-30 12:50:08 +00004974 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004975 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004976 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004977 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004978 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004979 }
Chris Lattnera2881962003-02-18 19:28:33 +00004980
Reid Spencere4d87aa2006-12-23 06:05:41 +00004981 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4982 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00004983 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004984 return R;
4985
Chris Lattner69d4ced2008-11-16 05:20:07 +00004986 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4987 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4988 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004989 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004990
4991 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004992 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004993 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004994 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004995 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4996 !isa<ICmpInst>(Op1C->getOperand(0))) {
4997 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004998 if (SrcTy == Op1C->getOperand(0)->getType() &&
4999 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00005000 // Only do this if the casts both really cause code to be
5001 // generated.
5002 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5003 I.getType(), TD) &&
5004 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5005 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005006 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5007 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005008 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005009 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005010 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005011 }
Chris Lattner99c65742007-10-24 05:38:08 +00005012 }
5013
5014
5015 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5016 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005017 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5018 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5019 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005020 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005021
Chris Lattner7e708292002-06-25 16:13:24 +00005022 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005023}
5024
Dan Gohman844731a2008-05-13 00:00:25 +00005025namespace {
5026
Chris Lattnerc317d392004-02-16 01:20:27 +00005027// XorSelf - Implements: X ^ X --> 0
5028struct XorSelf {
5029 Value *RHS;
5030 XorSelf(Value *rhs) : RHS(rhs) {}
5031 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5032 Instruction *apply(BinaryOperator &Xor) const {
5033 return &Xor;
5034 }
5035};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005036
Dan Gohman844731a2008-05-13 00:00:25 +00005037}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005038
Chris Lattner7e708292002-06-25 16:13:24 +00005039Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005040 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005041 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005042
Evan Chengd34af782008-03-25 20:07:13 +00005043 if (isa<UndefValue>(Op1)) {
5044 if (isa<UndefValue>(Op0))
5045 // Handle undef ^ undef -> 0 special case. This is a common
5046 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005047 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005048 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005049 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005050
Chris Lattnerc317d392004-02-16 01:20:27 +00005051 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005052 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005053 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005054 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005055 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005056
5057 // See if we can simplify any instructions used by the instruction whose sole
5058 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005059 if (SimplifyDemandedInstructionBits(I))
5060 return &I;
5061 if (isa<VectorType>(I.getType()))
5062 if (isa<ConstantAggregateZero>(Op1))
5063 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005064
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005065 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005066 if (Value *NotOp = dyn_castNotVal(&I)) {
Evan Cheng85def162009-10-26 03:51:32 +00005067 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5068 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005069 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5070 if (Op0I->getOpcode() == Instruction::And ||
5071 Op0I->getOpcode() == Instruction::Or) {
Evan Cheng85def162009-10-26 03:51:32 +00005072 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00005073 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005074 Value *NotY =
5075 Builder->CreateNot(Op0I->getOperand(1),
5076 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005077 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005078 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005079 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005080 }
5081 }
5082 }
5083 }
5084
5085
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005086 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00005087 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005088 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005089 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005090 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005091 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005092
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005093 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005094 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005095 FCI->getOperand(0), FCI->getOperand(1));
5096 }
5097
Nick Lewycky517e1f52008-05-31 19:01:33 +00005098 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5099 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5100 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5101 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5102 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005103 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5104 (RHS == ConstantExpr::getCast(Opcode,
5105 ConstantInt::getTrue(*Context),
5106 Op0C->getDestTy()))) {
5107 CI->setPredicate(CI->getInversePredicate());
5108 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005109 }
5110 }
5111 }
5112 }
5113
Reid Spencere4d87aa2006-12-23 06:05:41 +00005114 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005115 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005116 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5117 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005118 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5119 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005120 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005121 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005122 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005123
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005124 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005125 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005126 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005127 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005128 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005129 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005130 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005131 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005132 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005133 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005134 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005135 Constant *C = ConstantInt::get(*Context,
5136 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005137 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005138
Chris Lattner7c4049c2004-01-12 19:35:11 +00005139 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005140 } else if (Op0I->getOpcode() == Instruction::Or) {
5141 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005142 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005143 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005144 // Anything in both C1 and C2 is known to be zero, remove it from
5145 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005146 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5147 NewRHS = ConstantExpr::getAnd(NewRHS,
5148 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005149 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005150 I.setOperand(0, Op0I->getOperand(0));
5151 I.setOperand(1, NewRHS);
5152 return &I;
5153 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005154 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005155 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005156 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005157
5158 // Try to fold constant and into select arguments.
5159 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005160 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005161 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005162 if (isa<PHINode>(Op0))
5163 if (Instruction *NV = FoldOpIntoPhi(I))
5164 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005165 }
5166
Dan Gohman186a6362009-08-12 16:04:34 +00005167 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005168 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005169 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005170
Dan Gohman186a6362009-08-12 16:04:34 +00005171 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005172 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005173 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005174
Chris Lattner318bf792007-03-18 22:51:34 +00005175
5176 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5177 if (Op1I) {
5178 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005179 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005180 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005181 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005182 I.swapOperands();
5183 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005184 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005185 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005186 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005187 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005188 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005189 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005190 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005191 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005192 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005193 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005194 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005195 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005196 std::swap(A, B);
5197 }
Chris Lattner318bf792007-03-18 22:51:34 +00005198 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005199 I.swapOperands(); // Simplified below.
5200 std::swap(Op0, Op1);
5201 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005202 }
Chris Lattner318bf792007-03-18 22:51:34 +00005203 }
5204
5205 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5206 if (Op0I) {
5207 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005208 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005209 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005210 if (A == Op1) // (B|A)^B == (A|B)^B
5211 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005212 if (B == Op1) // (A|B)^B == A & ~B
5213 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005214 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005215 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005216 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005217 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005218 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005219 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005220 if (A == Op1) // (A&B)^A -> (B&A)^A
5221 std::swap(A, B);
5222 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005223 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005224 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005225 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005226 }
Chris Lattner318bf792007-03-18 22:51:34 +00005227 }
5228
5229 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5230 if (Op0I && Op1I && Op0I->isShift() &&
5231 Op0I->getOpcode() == Op1I->getOpcode() &&
5232 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5233 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005234 Value *NewOp =
5235 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5236 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005237 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005238 Op1I->getOperand(1));
5239 }
5240
5241 if (Op0I && Op1I) {
5242 Value *A, *B, *C, *D;
5243 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005244 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5245 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005246 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005247 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005248 }
5249 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005250 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5251 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005252 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005253 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005254 }
5255
5256 // (A & B)^(C & D)
5257 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005258 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5259 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005260 // (X & Y)^(X & Y) -> (Y^Z) & X
5261 Value *X = 0, *Y = 0, *Z = 0;
5262 if (A == C)
5263 X = A, Y = B, Z = D;
5264 else if (A == D)
5265 X = A, Y = B, Z = C;
5266 else if (B == C)
5267 X = B, Y = A, Z = D;
5268 else if (B == D)
5269 X = B, Y = A, Z = C;
5270
5271 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005272 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005273 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005274 }
5275 }
5276 }
5277
Reid Spencere4d87aa2006-12-23 06:05:41 +00005278 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5279 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005280 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005281 return R;
5282
Chris Lattner6fc205f2006-05-05 06:39:07 +00005283 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005284 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005285 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005286 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5287 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005288 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005289 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005290 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5291 I.getType(), TD) &&
5292 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5293 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005294 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5295 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005296 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005297 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005298 }
Chris Lattner99c65742007-10-24 05:38:08 +00005299 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005300
Chris Lattner7e708292002-06-25 16:13:24 +00005301 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005302}
5303
Owen Andersond672ecb2009-07-03 00:17:18 +00005304static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005305 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005306 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005307}
Chris Lattnera96879a2004-09-29 17:40:11 +00005308
Dan Gohman6de29f82009-06-15 22:12:54 +00005309static bool HasAddOverflow(ConstantInt *Result,
5310 ConstantInt *In1, ConstantInt *In2,
5311 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005312 if (IsSigned)
5313 if (In2->getValue().isNegative())
5314 return Result->getValue().sgt(In1->getValue());
5315 else
5316 return Result->getValue().slt(In1->getValue());
5317 else
5318 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005319}
5320
Dan Gohman6de29f82009-06-15 22:12:54 +00005321/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005322/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005323static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005324 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005325 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005326 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005327
Dan Gohman6de29f82009-06-15 22:12:54 +00005328 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5329 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005330 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005331 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5332 ExtractElement(In1, Idx, Context),
5333 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005334 IsSigned))
5335 return true;
5336 }
5337 return false;
5338 }
5339
5340 return HasAddOverflow(cast<ConstantInt>(Result),
5341 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5342 IsSigned);
5343}
5344
5345static bool HasSubOverflow(ConstantInt *Result,
5346 ConstantInt *In1, ConstantInt *In2,
5347 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005348 if (IsSigned)
5349 if (In2->getValue().isNegative())
5350 return Result->getValue().slt(In1->getValue());
5351 else
5352 return Result->getValue().sgt(In1->getValue());
5353 else
5354 return Result->getValue().ugt(In1->getValue());
5355}
5356
Dan Gohman6de29f82009-06-15 22:12:54 +00005357/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5358/// overflowed for this type.
5359static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005360 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005361 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005362 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005363
5364 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5365 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005366 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005367 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5368 ExtractElement(In1, Idx, Context),
5369 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005370 IsSigned))
5371 return true;
5372 }
5373 return false;
5374 }
5375
5376 return HasSubOverflow(cast<ConstantInt>(Result),
5377 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5378 IsSigned);
5379}
5380
Chris Lattner574da9b2005-01-13 20:14:25 +00005381/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5382/// code necessary to compute the offset from the base pointer (without adding
5383/// in the base pointer). Return the result as a signed integer of intptr size.
5384static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005385 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005386 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson1d0be152009-08-13 21:58:54 +00005387 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Andersona7235ea2009-07-31 20:28:14 +00005388 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005389
5390 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005391 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005392 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005393
Gabor Greif177dd3f2008-06-12 21:37:33 +00005394 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5395 ++i, ++GTI) {
5396 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005397 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005398 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5399 if (OpC->isZero()) continue;
5400
5401 // Handle a struct index, which adds its field offset to the pointer.
5402 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5403 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5404
Chris Lattner74381062009-08-30 07:44:24 +00005405 Result = IC.Builder->CreateAdd(Result,
5406 ConstantInt::get(IntPtrTy, Size),
5407 GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005408 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005409 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005410
Owen Andersoneed707b2009-07-24 23:12:02 +00005411 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005412 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005413 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5414 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattner74381062009-08-30 07:44:24 +00005415 // Emit an add instruction.
5416 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005417 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005418 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005419 // Convert to correct type.
Chris Lattner74381062009-08-30 07:44:24 +00005420 if (Op->getType() != IntPtrTy)
5421 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattnere62f0212007-04-28 04:52:43 +00005422 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005423 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner74381062009-08-30 07:44:24 +00005424 // We'll let instcombine(mul) convert this to a shl if possible.
5425 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattnere62f0212007-04-28 04:52:43 +00005426 }
5427
5428 // Emit an add instruction.
Chris Lattner74381062009-08-30 07:44:24 +00005429 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner574da9b2005-01-13 20:14:25 +00005430 }
5431 return Result;
5432}
5433
Chris Lattner10c0d912008-04-22 02:53:33 +00005434
Dan Gohman8f080f02009-07-17 22:16:21 +00005435/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5436/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5437/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5438/// be complex, and scales are involved. The above expression would also be
5439/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5440/// This later form is less amenable to optimization though, and we are allowed
5441/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005442///
5443/// If we can't emit an optimized form for this expression, this returns null.
5444///
5445static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5446 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005447 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005448 gep_type_iterator GTI = gep_type_begin(GEP);
5449
5450 // Check to see if this gep only has a single variable index. If so, and if
5451 // any constant indices are a multiple of its scale, then we can compute this
5452 // in terms of the scale of the variable index. For example, if the GEP
5453 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5454 // because the expression will cross zero at the same point.
5455 unsigned i, e = GEP->getNumOperands();
5456 int64_t Offset = 0;
5457 for (i = 1; i != e; ++i, ++GTI) {
5458 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5459 // Compute the aggregate offset of constant indices.
5460 if (CI->isZero()) continue;
5461
5462 // Handle a struct index, which adds its field offset to the pointer.
5463 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5464 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5465 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005466 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005467 Offset += Size*CI->getSExtValue();
5468 }
5469 } else {
5470 // Found our variable index.
5471 break;
5472 }
5473 }
5474
5475 // If there are no variable indices, we must have a constant offset, just
5476 // evaluate it the general way.
5477 if (i == e) return 0;
5478
5479 Value *VariableIdx = GEP->getOperand(i);
5480 // Determine the scale factor of the variable element. For example, this is
5481 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005482 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005483
5484 // Verify that there are no other variable indices. If so, emit the hard way.
5485 for (++i, ++GTI; i != e; ++i, ++GTI) {
5486 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5487 if (!CI) return 0;
5488
5489 // Compute the aggregate offset of constant indices.
5490 if (CI->isZero()) continue;
5491
5492 // Handle a struct index, which adds its field offset to the pointer.
5493 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5494 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5495 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005496 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005497 Offset += Size*CI->getSExtValue();
5498 }
5499 }
5500
5501 // Okay, we know we have a single variable index, which must be a
5502 // pointer/array/vector index. If there is no offset, life is simple, return
5503 // the index.
5504 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5505 if (Offset == 0) {
5506 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5507 // we don't need to bother extending: the extension won't affect where the
5508 // computation crosses zero.
5509 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson1d0be152009-08-13 21:58:54 +00005510 VariableIdx = new TruncInst(VariableIdx,
5511 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005512 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005513 return VariableIdx;
5514 }
5515
5516 // Otherwise, there is an index. The computation we will do will be modulo
5517 // the pointer size, so get it.
5518 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5519
5520 Offset &= PtrSizeMask;
5521 VariableScale &= PtrSizeMask;
5522
5523 // To do this transformation, any constant index must be a multiple of the
5524 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5525 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5526 // multiple of the variable scale.
5527 int64_t NewOffs = Offset / (int64_t)VariableScale;
5528 if (Offset != NewOffs*(int64_t)VariableScale)
5529 return 0;
5530
5531 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson1d0be152009-08-13 21:58:54 +00005532 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner10c0d912008-04-22 02:53:33 +00005533 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005534 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005535 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005536 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005537 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005538 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005539}
5540
5541
Reid Spencere4d87aa2006-12-23 06:05:41 +00005542/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005543/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005544Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005545 ICmpInst::Predicate Cond,
5546 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005547 // Look through bitcasts.
5548 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5549 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005550
Chris Lattner574da9b2005-01-13 20:14:25 +00005551 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005552 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005553 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005554 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005555 // know pointers can't overflow since the gep is inbounds. See if we can
5556 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005557 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5558
5559 // If not, synthesize the offset the hard way.
5560 if (Offset == 0)
5561 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005562 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005563 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005564 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005565 // If the base pointers are different, but the indices are the same, just
5566 // compare the base pointer.
5567 if (PtrBase != GEPRHS->getOperand(0)) {
5568 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005569 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005570 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005571 if (IndicesTheSame)
5572 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5573 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5574 IndicesTheSame = false;
5575 break;
5576 }
5577
5578 // If all indices are the same, just compare the base pointers.
5579 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005580 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005581 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005582
5583 // Otherwise, the base pointers are different and the indices are
5584 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005585 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005586 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005587
Chris Lattnere9d782b2005-01-13 22:25:21 +00005588 // If one of the GEPs has all zero indices, recurse.
5589 bool AllZeros = true;
5590 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5591 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5592 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5593 AllZeros = false;
5594 break;
5595 }
5596 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005597 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5598 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005599
5600 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005601 AllZeros = true;
5602 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5603 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5604 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5605 AllZeros = false;
5606 break;
5607 }
5608 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005609 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005610
Chris Lattner4401c9c2005-01-14 00:20:05 +00005611 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5612 // If the GEPs only differ by one index, compare it.
5613 unsigned NumDifferences = 0; // Keep track of # differences.
5614 unsigned DiffOperand = 0; // The operand that differs.
5615 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5616 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005617 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5618 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005619 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005620 NumDifferences = 2;
5621 break;
5622 } else {
5623 if (NumDifferences++) break;
5624 DiffOperand = i;
5625 }
5626 }
5627
5628 if (NumDifferences == 0) // SAME GEP?
5629 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005630 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005631 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005632
Chris Lattner4401c9c2005-01-14 00:20:05 +00005633 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005634 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5635 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005636 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005637 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005638 }
5639 }
5640
Reid Spencere4d87aa2006-12-23 06:05:41 +00005641 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005642 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005643 if (TD &&
5644 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005645 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5646 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5647 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5648 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005649 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005650 }
5651 }
5652 return 0;
5653}
5654
Chris Lattnera5406232008-05-19 20:18:56 +00005655/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5656///
5657Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5658 Instruction *LHSI,
5659 Constant *RHSC) {
5660 if (!isa<ConstantFP>(RHSC)) return 0;
5661 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5662
5663 // Get the width of the mantissa. We don't want to hack on conversions that
5664 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005665 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005666 if (MantissaWidth == -1) return 0; // Unknown.
5667
5668 // Check to see that the input is converted from an integer type that is small
5669 // enough that preserves all bits. TODO: check here for "known" sign bits.
5670 // 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 +00005671 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005672
5673 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005674 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5675 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005676 ++InputSize;
5677
5678 // If the conversion would lose info, don't hack on this.
5679 if ((int)InputSize > MantissaWidth)
5680 return 0;
5681
5682 // Otherwise, we can potentially simplify the comparison. We know that it
5683 // will always come through as an integer value and we know the constant is
5684 // not a NAN (it would have been previously simplified).
5685 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5686
5687 ICmpInst::Predicate Pred;
5688 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005689 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005690 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005691 case FCmpInst::FCMP_OEQ:
5692 Pred = ICmpInst::ICMP_EQ;
5693 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005694 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005695 case FCmpInst::FCMP_OGT:
5696 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5697 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005698 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005699 case FCmpInst::FCMP_OGE:
5700 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5701 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005702 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005703 case FCmpInst::FCMP_OLT:
5704 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5705 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005706 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005707 case FCmpInst::FCMP_OLE:
5708 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5709 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005710 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005711 case FCmpInst::FCMP_ONE:
5712 Pred = ICmpInst::ICMP_NE;
5713 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005714 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005715 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005716 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005717 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005718 }
5719
5720 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5721
5722 // Now we know that the APFloat is a normal number, zero or inf.
5723
Chris Lattner85162782008-05-20 03:50:52 +00005724 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005725 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005726 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005727
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005728 if (!LHSUnsigned) {
5729 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5730 // and large values.
5731 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5732 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5733 APFloat::rmNearestTiesToEven);
5734 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5735 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5736 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005737 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5738 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005739 }
5740 } else {
5741 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5742 // +INF and large values.
5743 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5744 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5745 APFloat::rmNearestTiesToEven);
5746 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5747 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5748 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005749 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5750 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005751 }
Chris Lattnera5406232008-05-19 20:18:56 +00005752 }
5753
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005754 if (!LHSUnsigned) {
5755 // See if the RHS value is < SignedMin.
5756 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5757 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5758 APFloat::rmNearestTiesToEven);
5759 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5760 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5761 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005762 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5763 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005764 }
Chris Lattnera5406232008-05-19 20:18:56 +00005765 }
5766
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005767 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5768 // [0, UMAX], but it may still be fractional. See if it is fractional by
5769 // casting the FP value to the integer value and back, checking for equality.
5770 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005771 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005772 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5773 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005774 if (!RHS.isZero()) {
5775 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005776 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5777 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005778 if (!Equal) {
5779 // If we had a comparison against a fractional value, we have to adjust
5780 // the compare predicate and sometimes the value. RHSC is rounded towards
5781 // zero at this point.
5782 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005783 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005784 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005785 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005786 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005787 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005788 case ICmpInst::ICMP_ULE:
5789 // (float)int <= 4.4 --> int <= 4
5790 // (float)int <= -4.4 --> false
5791 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005792 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005793 break;
5794 case ICmpInst::ICMP_SLE:
5795 // (float)int <= 4.4 --> int <= 4
5796 // (float)int <= -4.4 --> int < -4
5797 if (RHS.isNegative())
5798 Pred = ICmpInst::ICMP_SLT;
5799 break;
5800 case ICmpInst::ICMP_ULT:
5801 // (float)int < -4.4 --> false
5802 // (float)int < 4.4 --> int <= 4
5803 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005804 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005805 Pred = ICmpInst::ICMP_ULE;
5806 break;
5807 case ICmpInst::ICMP_SLT:
5808 // (float)int < -4.4 --> int < -4
5809 // (float)int < 4.4 --> int <= 4
5810 if (!RHS.isNegative())
5811 Pred = ICmpInst::ICMP_SLE;
5812 break;
5813 case ICmpInst::ICMP_UGT:
5814 // (float)int > 4.4 --> int > 4
5815 // (float)int > -4.4 --> true
5816 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005817 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005818 break;
5819 case ICmpInst::ICMP_SGT:
5820 // (float)int > 4.4 --> int > 4
5821 // (float)int > -4.4 --> int >= -4
5822 if (RHS.isNegative())
5823 Pred = ICmpInst::ICMP_SGE;
5824 break;
5825 case ICmpInst::ICMP_UGE:
5826 // (float)int >= -4.4 --> true
5827 // (float)int >= 4.4 --> int > 4
5828 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005829 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005830 Pred = ICmpInst::ICMP_UGT;
5831 break;
5832 case ICmpInst::ICMP_SGE:
5833 // (float)int >= -4.4 --> int >= -4
5834 // (float)int >= 4.4 --> int > 4
5835 if (!RHS.isNegative())
5836 Pred = ICmpInst::ICMP_SGT;
5837 break;
5838 }
Chris Lattnera5406232008-05-19 20:18:56 +00005839 }
5840 }
5841
5842 // Lower this FP comparison into an appropriate integer version of the
5843 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005844 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005845}
5846
Reid Spencere4d87aa2006-12-23 06:05:41 +00005847Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5848 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005849 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005850
Chris Lattner58e97462007-01-14 19:42:17 +00005851 // Fold trivial predicates.
5852 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005853 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005854 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005855 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005856
5857 // Simplify 'fcmp pred X, X'
5858 if (Op0 == Op1) {
5859 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005860 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005861 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5862 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5863 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Chris Lattner9e17b632009-09-02 05:12:37 +00005864 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005865 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5866 case FCmpInst::FCMP_OLT: // True if ordered and less than
5867 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Chris Lattner9e17b632009-09-02 05:12:37 +00005868 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005869
5870 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5871 case FCmpInst::FCMP_ULT: // True if unordered or less than
5872 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5873 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5874 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5875 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005876 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005877 return &I;
5878
5879 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5880 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5881 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5882 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5883 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5884 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005885 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005886 return &I;
5887 }
5888 }
5889
Reid Spencere4d87aa2006-12-23 06:05:41 +00005890 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00005891 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005892
Reid Spencere4d87aa2006-12-23 06:05:41 +00005893 // Handle fcmp with constant RHS
5894 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005895 // If the constant is a nan, see if we can fold the comparison based on it.
5896 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5897 if (CFP->getValueAPF().isNaN()) {
5898 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005899 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005900 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5901 "Comparison must be either ordered or unordered!");
5902 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005903 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005904 }
5905 }
5906
Reid Spencere4d87aa2006-12-23 06:05:41 +00005907 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5908 switch (LHSI->getOpcode()) {
5909 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005910 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5911 // block. If in the same block, we're encouraging jump threading. If
5912 // not, we are just pessimizing the code by making an i1 phi.
5913 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00005914 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005915 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005916 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005917 case Instruction::SIToFP:
5918 case Instruction::UIToFP:
5919 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5920 return NV;
5921 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005922 case Instruction::Select:
5923 // If either operand of the select is a constant, we can fold the
5924 // comparison into the select arms, which will cause one to be
5925 // constant folded and the select turned into a bitwise or.
5926 Value *Op1 = 0, *Op2 = 0;
5927 if (LHSI->hasOneUse()) {
5928 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5929 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005930 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005931 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005932 Op2 = Builder->CreateFCmp(I.getPredicate(),
5933 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005934 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5935 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005936 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005937 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005938 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5939 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005940 }
5941 }
5942
5943 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005944 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005945 break;
5946 }
5947 }
5948
5949 return Changed ? &I : 0;
5950}
5951
5952Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5953 bool Changed = SimplifyCompare(I);
5954 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5955 const Type *Ty = Op0->getType();
5956
5957 // icmp X, X
5958 if (Op0 == Op1)
Chris Lattner9e17b632009-09-02 05:12:37 +00005959 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005960 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005961
5962 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00005963 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005964
Reid Spencere4d87aa2006-12-23 06:05:41 +00005965 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005966 // addresses never equal each other! We already know that Op0 != Op1.
Chris Lattnerbbc33852009-10-05 02:47:47 +00005967 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
Misha Brukmanfd939082005-04-21 23:48:37 +00005968 isa<ConstantPointerNull>(Op0)) &&
Chris Lattnerbbc33852009-10-05 02:47:47 +00005969 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005970 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00005971 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005972 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005973
Reid Spencere4d87aa2006-12-23 06:05:41 +00005974 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00005975 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005976 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005977 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005978 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00005979 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00005980 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005981 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005982 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005983 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005984
Reid Spencere4d87aa2006-12-23 06:05:41 +00005985 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005986 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005987 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005988 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00005989 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005990 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005991 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005992 case ICmpInst::ICMP_SGT:
5993 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005994 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005995 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00005996 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005997 return BinaryOperator::CreateAnd(Not, Op0);
5998 }
5999 case ICmpInst::ICMP_UGE:
6000 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6001 // FALL THROUGH
6002 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00006003 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006004 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006005 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006006 case ICmpInst::ICMP_SGE:
6007 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6008 // FALL THROUGH
6009 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00006010 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006011 return BinaryOperator::CreateOr(Not, Op0);
6012 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006013 }
Chris Lattner8b170942002-08-09 23:47:40 +00006014 }
6015
Dan Gohman1c8491e2009-04-25 17:12:48 +00006016 unsigned BitWidth = 0;
6017 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006018 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6019 else if (Ty->isIntOrIntVector())
6020 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006021
6022 bool isSignBit = false;
6023
Dan Gohman81b28ce2008-09-16 18:46:06 +00006024 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006025 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006026 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006027
Chris Lattnerb6566012008-01-05 01:18:20 +00006028 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6029 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006030 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006031 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006032 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006033 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006034
Dan Gohman81b28ce2008-09-16 18:46:06 +00006035 // If we have an icmp le or icmp ge instruction, turn it into the
6036 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6037 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006038 switch (I.getPredicate()) {
6039 default: break;
6040 case ICmpInst::ICMP_ULE:
6041 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006042 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006043 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006044 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006045 case ICmpInst::ICMP_SLE:
6046 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006047 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006048 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006049 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006050 case ICmpInst::ICMP_UGE:
6051 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006052 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006053 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006054 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006055 case ICmpInst::ICMP_SGE:
6056 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006057 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006058 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006059 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006060 }
6061
Chris Lattner183661e2008-07-11 05:40:05 +00006062 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006063 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006064 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006065 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6066 }
6067
6068 // See if we can fold the comparison based on range information we can get
6069 // by checking whether bits are known to be zero or one in the input.
6070 if (BitWidth != 0) {
6071 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6072 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6073
6074 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006075 isSignBit ? APInt::getSignBit(BitWidth)
6076 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006077 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006078 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006079 if (SimplifyDemandedBits(I.getOperandUse(1),
6080 APInt::getAllOnesValue(BitWidth),
6081 Op1KnownZero, Op1KnownOne, 0))
6082 return &I;
6083
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006084 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006085 // in. Compute the Min, Max and RHS values based on the known bits. For the
6086 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006087 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6088 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewycky4a134af2009-10-25 05:20:17 +00006089 if (I.isSigned()) {
Dan Gohman1c8491e2009-04-25 17:12:48 +00006090 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6091 Op0Min, Op0Max);
6092 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6093 Op1Min, Op1Max);
6094 } else {
6095 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6096 Op0Min, Op0Max);
6097 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6098 Op1Min, Op1Max);
6099 }
6100
Chris Lattner183661e2008-07-11 05:40:05 +00006101 // If Min and Max are known to be the same, then SimplifyDemandedBits
6102 // figured out that the LHS is a constant. Just constant fold this now so
6103 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006104 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006105 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006106 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006107 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006108 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006109 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006110
Chris Lattner183661e2008-07-11 05:40:05 +00006111 // Based on the range information we know about the LHS, see if we can
6112 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006113 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006114 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006115 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006116 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006117 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006118 break;
6119 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006120 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006121 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006122 break;
6123 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006124 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006125 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006126 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006127 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006128 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006129 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006130 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6131 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006132 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006133 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006134
6135 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6136 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006137 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006138 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006139 }
Chris Lattner84dff672008-07-11 05:08:55 +00006140 break;
6141 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006142 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006143 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006144 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006145 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006146
6147 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006148 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006149 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6150 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006151 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006152 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006153
6154 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6155 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006156 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006157 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006158 }
Chris Lattner84dff672008-07-11 05:08:55 +00006159 break;
6160 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006161 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006162 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006163 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006164 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006165 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006166 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006167 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6168 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006169 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006170 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006171 }
Chris Lattner84dff672008-07-11 05:08:55 +00006172 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006173 case ICmpInst::ICMP_SGT:
6174 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006175 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006176 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006177 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006178
6179 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006180 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006181 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6182 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006183 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006184 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006185 }
6186 break;
6187 case ICmpInst::ICMP_SGE:
6188 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6189 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006190 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006191 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006192 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006193 break;
6194 case ICmpInst::ICMP_SLE:
6195 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6196 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006197 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006198 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006199 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006200 break;
6201 case ICmpInst::ICMP_UGE:
6202 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6203 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006204 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006205 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006206 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006207 break;
6208 case ICmpInst::ICMP_ULE:
6209 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6210 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006211 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006212 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006213 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006214 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006215 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006216
6217 // Turn a signed comparison into an unsigned one if both operands
6218 // are known to have the same sign.
Nick Lewycky4a134af2009-10-25 05:20:17 +00006219 if (I.isSigned() &&
Dan Gohman1c8491e2009-04-25 17:12:48 +00006220 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6221 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006222 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006223 }
6224
6225 // Test if the ICmpInst instruction is used exclusively by a select as
6226 // part of a minimum or maximum operation. If so, refrain from doing
6227 // any other folding. This helps out other analyses which understand
6228 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6229 // and CodeGen. And in this case, at least one of the comparison
6230 // operands has at least one user besides the compare (the select),
6231 // which would often largely negate the benefit of folding anyway.
6232 if (I.hasOneUse())
6233 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6234 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6235 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6236 return 0;
6237
6238 // See if we are doing a comparison between a constant and an instruction that
6239 // can be folded into the comparison.
6240 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006241 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006242 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006243 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006244 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006245 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6246 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006247 }
6248
Chris Lattner01deb9d2007-04-03 17:43:25 +00006249 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006250 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6251 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6252 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006253 case Instruction::GetElementPtr:
6254 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006255 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006256 bool isAllZeros = true;
6257 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6258 if (!isa<Constant>(LHSI->getOperand(i)) ||
6259 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6260 isAllZeros = false;
6261 break;
6262 }
6263 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006264 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006265 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006266 }
6267 break;
6268
Chris Lattner6970b662005-04-23 15:31:55 +00006269 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006270 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006271 // block. If in the same block, we're encouraging jump threading. If
6272 // not, we are just pessimizing the code by making an i1 phi.
6273 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006274 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006275 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006276 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006277 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006278 // If either operand of the select is a constant, we can fold the
6279 // comparison into the select arms, which will cause one to be
6280 // constant folded and the select turned into a bitwise or.
6281 Value *Op1 = 0, *Op2 = 0;
6282 if (LHSI->hasOneUse()) {
6283 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6284 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006285 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006286 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006287 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6288 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006289 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6290 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006291 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006292 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006293 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6294 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006295 }
6296 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006297
Chris Lattner6970b662005-04-23 15:31:55 +00006298 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006299 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006300 break;
6301 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006302 case Instruction::Call:
6303 // If we have (malloc != null), and if the malloc has a single use, we
6304 // can assume it is successful and remove the malloc.
6305 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6306 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez68afa542009-10-21 19:11:40 +00006307 // Need to explicitly erase malloc call here, instead of adding it to
6308 // Worklist, because it won't get DCE'd from the Worklist since
6309 // isInstructionTriviallyDead() returns false for function calls.
6310 // It is OK to replace LHSI/MallocCall with Undef because the
6311 // instruction that uses it will be erased via Worklist.
6312 if (extractMallocCall(LHSI)) {
6313 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6314 EraseInstFromFunction(*LHSI);
6315 return ReplaceInstUsesWith(I,
Victor Hernandez83d63912009-09-18 22:35:49 +00006316 ConstantInt::get(Type::getInt1Ty(*Context),
6317 !I.isTrueWhenEqual()));
Victor Hernandez68afa542009-10-21 19:11:40 +00006318 }
6319 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6320 if (MallocCall->hasOneUse()) {
6321 MallocCall->replaceAllUsesWith(
6322 UndefValue::get(MallocCall->getType()));
6323 EraseInstFromFunction(*MallocCall);
6324 Worklist.Add(LHSI); // The malloc's bitcast use.
6325 return ReplaceInstUsesWith(I,
6326 ConstantInt::get(Type::getInt1Ty(*Context),
6327 !I.isTrueWhenEqual()));
6328 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006329 }
6330 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006331 }
Chris Lattner6970b662005-04-23 15:31:55 +00006332 }
6333
Reid Spencere4d87aa2006-12-23 06:05:41 +00006334 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006335 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006336 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006337 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006338 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006339 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6340 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006341 return NI;
6342
Reid Spencere4d87aa2006-12-23 06:05:41 +00006343 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006344 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6345 // now.
6346 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6347 if (isa<PointerType>(Op0->getType()) &&
6348 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006349 // We keep moving the cast from the left operand over to the right
6350 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006351 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006352
Chris Lattner57d86372007-01-06 01:45:59 +00006353 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6354 // so eliminate it as well.
6355 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6356 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006357
Chris Lattnerde90b762003-11-03 04:25:02 +00006358 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006359 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006360 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006361 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006362 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006363 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006364 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006365 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006366 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006367 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006368 }
Chris Lattner57d86372007-01-06 01:45:59 +00006369 }
6370
6371 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006372 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006373 // This comes up when you have code like
6374 // int X = A < B;
6375 // if (X) ...
6376 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006377 // with a constant or another cast from the same type.
6378 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006379 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006380 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006381 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006382
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006383 // See if it's the same type of instruction on the left and right.
6384 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6385 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006386 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006387 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006388 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006389 default: break;
6390 case Instruction::Add:
6391 case Instruction::Sub:
6392 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006393 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006394 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006395 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006396 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6397 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6398 if (CI->getValue().isSignBit()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006399 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006400 ? I.getUnsignedPredicate()
6401 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006402 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006403 Op1I->getOperand(0));
6404 }
6405
6406 if (CI->getValue().isMaxSignedValue()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006407 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006408 ? I.getUnsignedPredicate()
6409 : I.getSignedPredicate();
6410 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006411 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006412 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006413 }
6414 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006415 break;
6416 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006417 if (!I.isEquality())
6418 break;
6419
Nick Lewycky5d52c452008-08-21 05:56:10 +00006420 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6421 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6422 // Mask = -1 >> count-trailing-zeros(Cst).
6423 if (!CI->isZero() && !CI->isOne()) {
6424 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006425 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006426 APInt::getLowBitsSet(AP.getBitWidth(),
6427 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006428 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006429 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6430 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006431 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006432 }
6433 }
6434 break;
6435 }
6436 }
6437 }
6438 }
6439
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006440 // ~x < ~y --> y < x
6441 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006442 if (match(Op0, m_Not(m_Value(A))) &&
6443 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006444 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006445 }
6446
Chris Lattner65b72ba2006-09-18 04:22:48 +00006447 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006448 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006449
6450 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006451 if (match(Op0, m_Neg(m_Value(A))) &&
6452 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006453 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006454
Dan Gohman4ae51262009-08-12 16:23:25 +00006455 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006456 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6457 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006458 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006459 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006460 }
6461
Dan Gohman4ae51262009-08-12 16:23:25 +00006462 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006463 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006464 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006465 if (match(B, m_ConstantInt(C1)) &&
6466 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006467 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006468 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006469 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6470 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006471 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006472
6473 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006474 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6475 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6476 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6477 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006478 }
6479 }
6480
Dan Gohman4ae51262009-08-12 16:23:25 +00006481 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006482 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006483 // A == (A^B) -> B == 0
6484 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006485 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006486 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006487 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006488
6489 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006490 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006491 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006492 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006493
6494 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006495 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006496 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006497 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006498
Chris Lattner9c2328e2006-11-14 06:06:06 +00006499 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6500 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006501 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6502 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006503 Value *X = 0, *Y = 0, *Z = 0;
6504
6505 if (A == C) {
6506 X = B; Y = D; Z = A;
6507 } else if (A == D) {
6508 X = B; Y = C; Z = A;
6509 } else if (B == C) {
6510 X = A; Y = D; Z = B;
6511 } else if (B == D) {
6512 X = A; Y = C; Z = B;
6513 }
6514
6515 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006516 Op1 = Builder->CreateXor(X, Y, "tmp");
6517 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006518 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006519 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006520 return &I;
6521 }
6522 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006523 }
Chris Lattner7e708292002-06-25 16:13:24 +00006524 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006525}
6526
Chris Lattner562ef782007-06-20 23:46:26 +00006527
6528/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6529/// and CmpRHS are both known to be integer constants.
6530Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6531 ConstantInt *DivRHS) {
6532 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6533 const APInt &CmpRHSV = CmpRHS->getValue();
6534
6535 // FIXME: If the operand types don't match the type of the divide
6536 // then don't attempt this transform. The code below doesn't have the
6537 // logic to deal with a signed divide and an unsigned compare (and
6538 // vice versa). This is because (x /s C1) <s C2 produces different
6539 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6540 // (x /u C1) <u C2. Simply casting the operands and result won't
6541 // work. :( The if statement below tests that condition and bails
6542 // if it finds it.
6543 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewycky4a134af2009-10-25 05:20:17 +00006544 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Chris Lattner562ef782007-06-20 23:46:26 +00006545 return 0;
6546 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006547 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006548 if (DivIsSigned && DivRHS->isAllOnesValue())
6549 return 0; // The overflow computation also screws up here
6550 if (DivRHS->isOne())
6551 return 0; // Not worth bothering, and eliminates some funny cases
6552 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006553
6554 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6555 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6556 // C2 (CI). By solving for X we can turn this into a range check
6557 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006558 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006559
6560 // Determine if the product overflows by seeing if the product is
6561 // not equal to the divide. Make sure we do the same kind of divide
6562 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006563 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6564 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006565
6566 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006567 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006568
Chris Lattner1dbfd482007-06-21 18:11:19 +00006569 // Figure out the interval that is being checked. For example, a comparison
6570 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6571 // Compute this interval based on the constants involved and the signedness of
6572 // the compare/divide. This computes a half-open interval, keeping track of
6573 // whether either value in the interval overflows. After analysis each
6574 // overflow variable is set to 0 if it's corresponding bound variable is valid
6575 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6576 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006577 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006578
Chris Lattner562ef782007-06-20 23:46:26 +00006579 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006580 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006581 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006582 HiOverflow = LoOverflow = ProdOV;
6583 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006584 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006585 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006586 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006587 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006588 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006589 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006590 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006591 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6592 HiOverflow = LoOverflow = ProdOV;
6593 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006594 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006595 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006596 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006597 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006598 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6599 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006600 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006601 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006602 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006603 true) ? -1 : 0;
6604 }
Chris Lattner562ef782007-06-20 23:46:26 +00006605 }
Dan Gohman76491272008-02-13 22:09:18 +00006606 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006607 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006608 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006609 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006610 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006611 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6612 HiOverflow = 1; // [INTMIN+1, overflow)
6613 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6614 }
Dan Gohman76491272008-02-13 22:09:18 +00006615 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006616 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006617 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006618 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006619 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006620 LoOverflow = AddWithOverflow(LoBound, HiBound,
6621 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006622 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006623 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6624 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006625 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006626 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006627 }
6628
Chris Lattner1dbfd482007-06-21 18:11:19 +00006629 // Dividing by a negative swaps the condition. LT <-> GT
6630 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006631 }
6632
6633 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006634 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006635 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006636 case ICmpInst::ICMP_EQ:
6637 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006638 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006639 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006640 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006641 ICmpInst::ICMP_UGE, X, LoBound);
6642 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006643 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006644 ICmpInst::ICMP_ULT, X, HiBound);
6645 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006646 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006647 case ICmpInst::ICMP_NE:
6648 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006649 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006650 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006651 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006652 ICmpInst::ICMP_ULT, X, LoBound);
6653 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006654 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006655 ICmpInst::ICMP_UGE, X, HiBound);
6656 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006657 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006658 case ICmpInst::ICMP_ULT:
6659 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006660 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006661 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006662 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006663 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006664 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006665 case ICmpInst::ICMP_UGT:
6666 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006667 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006668 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006669 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006670 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006671 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006672 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006673 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006674 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006675 }
6676}
6677
6678
Chris Lattner01deb9d2007-04-03 17:43:25 +00006679/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6680///
6681Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6682 Instruction *LHSI,
6683 ConstantInt *RHS) {
6684 const APInt &RHSV = RHS->getValue();
6685
6686 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006687 case Instruction::Trunc:
6688 if (ICI.isEquality() && LHSI->hasOneUse()) {
6689 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6690 // of the high bits truncated out of x are known.
6691 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6692 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6693 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6694 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6695 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6696
6697 // If all the high bits are known, we can do this xform.
6698 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6699 // Pull in the high bits from known-ones set.
6700 APInt NewRHS(RHS->getValue());
6701 NewRHS.zext(SrcBits);
6702 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006703 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006704 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006705 }
6706 }
6707 break;
6708
Duncan Sands0091bf22007-04-04 06:42:45 +00006709 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006710 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6711 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6712 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006713 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6714 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006715 Value *CompareVal = LHSI->getOperand(0);
6716
6717 // If the sign bit of the XorCST is not set, there is no change to
6718 // the operation, just stop using the Xor.
6719 if (!XorCST->getValue().isNegative()) {
6720 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006721 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006722 return &ICI;
6723 }
6724
6725 // Was the old condition true if the operand is positive?
6726 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6727
6728 // If so, the new one isn't.
6729 isTrueIfPositive ^= true;
6730
6731 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006732 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006733 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006734 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006735 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006736 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006737 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006738
6739 if (LHSI->hasOneUse()) {
6740 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6741 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6742 const APInt &SignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006743 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006744 ? ICI.getUnsignedPredicate()
6745 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006746 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006747 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006748 }
6749
6750 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006751 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006752 const APInt &NotSignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006753 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006754 ? ICI.getUnsignedPredicate()
6755 : ICI.getSignedPredicate();
6756 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006757 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006758 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006759 }
6760 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006761 }
6762 break;
6763 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6764 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6765 LHSI->getOperand(0)->hasOneUse()) {
6766 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6767
6768 // If the LHS is an AND of a truncating cast, we can widen the
6769 // and/compare to be the input width without changing the value
6770 // produced, eliminating a cast.
6771 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6772 // We can do this transformation if either the AND constant does not
6773 // have its sign bit set or if it is an equality comparison.
6774 // Extending a relational comparison when we're checking the sign
6775 // bit would not work.
6776 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006777 (ICI.isEquality() ||
6778 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006779 uint32_t BitWidth =
6780 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6781 APInt NewCST = AndCST->getValue();
6782 NewCST.zext(BitWidth);
6783 APInt NewCI = RHSV;
6784 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006785 Value *NewAnd =
6786 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006787 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006788 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006789 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006790 }
6791 }
6792
6793 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6794 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6795 // happens a LOT in code produced by the C front-end, for bitfield
6796 // access.
6797 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6798 if (Shift && !Shift->isShift())
6799 Shift = 0;
6800
6801 ConstantInt *ShAmt;
6802 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6803 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6804 const Type *AndTy = AndCST->getType(); // Type of the and.
6805
6806 // We can fold this as long as we can't shift unknown bits
6807 // into the mask. This can only happen with signed shift
6808 // rights, as they sign-extend.
6809 if (ShAmt) {
6810 bool CanFold = Shift->isLogicalShift();
6811 if (!CanFold) {
6812 // To test for the bad case of the signed shr, see if any
6813 // of the bits shifted in could be tested after the mask.
6814 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6815 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6816
6817 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6818 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6819 AndCST->getValue()) == 0)
6820 CanFold = true;
6821 }
6822
6823 if (CanFold) {
6824 Constant *NewCst;
6825 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006826 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006827 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006828 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006829
6830 // Check to see if we are shifting out any of the bits being
6831 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006832 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006833 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006834 // If we shifted bits out, the fold is not going to work out.
6835 // As a special case, check to see if this means that the
6836 // result is always true or false now.
6837 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006838 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006839 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006840 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006841 } else {
6842 ICI.setOperand(1, NewCst);
6843 Constant *NewAndCST;
6844 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006845 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006846 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006847 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006848 LHSI->setOperand(1, NewAndCST);
6849 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006850 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006851 return &ICI;
6852 }
6853 }
6854 }
6855
6856 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6857 // preferable because it allows the C<<Y expression to be hoisted out
6858 // of a loop if Y is invariant and X is not.
6859 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006860 ICI.isEquality() && !Shift->isArithmeticShift() &&
6861 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006862 // Compute C << Y.
6863 Value *NS;
6864 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006865 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006866 } else {
6867 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006868 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006869 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006870
6871 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006872 Value *NewAnd =
6873 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006874
6875 ICI.setOperand(0, NewAnd);
6876 return &ICI;
6877 }
6878 }
6879 break;
6880
Chris Lattnera0141b92007-07-15 20:42:37 +00006881 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6882 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6883 if (!ShAmt) break;
6884
6885 uint32_t TypeBits = RHSV.getBitWidth();
6886
6887 // Check that the shift amount is in range. If not, don't perform
6888 // undefined shifts. When the shift is visited it will be
6889 // simplified.
6890 if (ShAmt->uge(TypeBits))
6891 break;
6892
6893 if (ICI.isEquality()) {
6894 // If we are comparing against bits always shifted out, the
6895 // comparison cannot succeed.
6896 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006897 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006898 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006899 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6900 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006901 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006902 return ReplaceInstUsesWith(ICI, Cst);
6903 }
6904
6905 if (LHSI->hasOneUse()) {
6906 // Otherwise strength reduce the shift into an and.
6907 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6908 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006909 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006910 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006911
Chris Lattner74381062009-08-30 07:44:24 +00006912 Value *And =
6913 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006914 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006915 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006916 }
6917 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006918
6919 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6920 bool TrueIfSigned = false;
6921 if (LHSI->hasOneUse() &&
6922 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6923 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006924 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006925 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00006926 Value *And =
6927 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006928 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006929 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006930 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006931 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006932 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006933
6934 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006935 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006936 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006937 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006938 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006939
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006940 // Check that the shift amount is in range. If not, don't perform
6941 // undefined shifts. When the shift is visited it will be
6942 // simplified.
6943 uint32_t TypeBits = RHSV.getBitWidth();
6944 if (ShAmt->uge(TypeBits))
6945 break;
6946
6947 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006948
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006949 // If we are comparing against bits always shifted out, the
6950 // comparison cannot succeed.
6951 APInt Comp = RHSV << ShAmtVal;
6952 if (LHSI->getOpcode() == Instruction::LShr)
6953 Comp = Comp.lshr(ShAmtVal);
6954 else
6955 Comp = Comp.ashr(ShAmtVal);
6956
6957 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6958 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006959 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006960 return ReplaceInstUsesWith(ICI, Cst);
6961 }
6962
6963 // Otherwise, check to see if the bits shifted out are known to be zero.
6964 // If so, we can compare against the unshifted value:
6965 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006966 if (LHSI->hasOneUse() &&
6967 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006968 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006969 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006970 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006971 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006972
Evan Chengf30752c2008-04-23 00:38:06 +00006973 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006974 // Otherwise strength reduce the shift into an and.
6975 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00006976 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006977
Chris Lattner74381062009-08-30 07:44:24 +00006978 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6979 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006980 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00006981 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006982 }
6983 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006984 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006985
6986 case Instruction::SDiv:
6987 case Instruction::UDiv:
6988 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6989 // Fold this div into the comparison, producing a range check.
6990 // Determine, based on the divide type, what the range is being
6991 // checked. If there is an overflow on the low or high side, remember
6992 // it, otherwise compute the range [low, hi) bounding the new value.
6993 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006994 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6995 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6996 DivRHS))
6997 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006998 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006999
7000 case Instruction::Add:
7001 // Fold: icmp pred (add, X, C1), C2
7002
7003 if (!ICI.isEquality()) {
7004 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7005 if (!LHSC) break;
7006 const APInt &LHSV = LHSC->getValue();
7007
7008 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7009 .subtract(LHSV);
7010
Nick Lewycky4a134af2009-10-25 05:20:17 +00007011 if (ICI.isSigned()) {
Nick Lewycky5be29202008-02-03 16:33:09 +00007012 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007013 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007014 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007015 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007016 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007017 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007018 }
7019 } else {
7020 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007021 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007022 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007023 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007024 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007025 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007026 }
7027 }
7028 }
7029 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007030 }
7031
7032 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7033 if (ICI.isEquality()) {
7034 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7035
7036 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7037 // the second operand is a constant, simplify a bit.
7038 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7039 switch (BO->getOpcode()) {
7040 case Instruction::SRem:
7041 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7042 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7043 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7044 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007045 Value *NewRem =
7046 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7047 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007048 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007049 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007050 }
7051 }
7052 break;
7053 case Instruction::Add:
7054 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7055 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7056 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007057 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007058 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007059 } else if (RHSV == 0) {
7060 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7061 // efficiently invertible, or if the add has just this one use.
7062 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7063
Dan Gohman186a6362009-08-12 16:04:34 +00007064 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007065 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007066 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007067 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007068 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007069 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007070 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007071 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007072 }
7073 }
7074 break;
7075 case Instruction::Xor:
7076 // For the xor case, we can xor two constants together, eliminating
7077 // the explicit xor.
7078 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007079 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007080 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007081
7082 // FALLTHROUGH
7083 case Instruction::Sub:
7084 // Replace (([sub|xor] A, B) != 0) with (A != B)
7085 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007086 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007087 BO->getOperand(1));
7088 break;
7089
7090 case Instruction::Or:
7091 // If bits are being or'd in that are not present in the constant we
7092 // are comparing against, then the comparison could never succeed!
7093 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007094 Constant *NotCI = ConstantExpr::getNot(RHS);
7095 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007096 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007097 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007098 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007099 }
7100 break;
7101
7102 case Instruction::And:
7103 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7104 // If bits are being compared against that are and'd out, then the
7105 // comparison can never succeed!
7106 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007107 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007108 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007109 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007110
7111 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7112 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007113 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007114 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007115 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007116
7117 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007118 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007119 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007120 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007121 ICmpInst::Predicate pred = isICMP_NE ?
7122 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007123 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007124 }
7125
7126 // ((X & ~7) == 0) --> X < 8
7127 if (RHSV == 0 && isHighOnes(BOC)) {
7128 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007129 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007130 ICmpInst::Predicate pred = isICMP_NE ?
7131 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007132 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007133 }
7134 }
7135 default: break;
7136 }
7137 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7138 // Handle icmp {eq|ne} <intrinsic>, intcst.
7139 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007140 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007141 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007142 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007143 return &ICI;
7144 }
7145 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007146 }
7147 return 0;
7148}
7149
7150/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7151/// We only handle extending casts so far.
7152///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007153Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7154 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007155 Value *LHSCIOp = LHSCI->getOperand(0);
7156 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007157 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007158 Value *RHSCIOp;
7159
Chris Lattner8c756c12007-05-05 22:41:33 +00007160 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7161 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007162 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7163 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007164 cast<IntegerType>(DestTy)->getBitWidth()) {
7165 Value *RHSOp = 0;
7166 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007167 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007168 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7169 RHSOp = RHSC->getOperand(0);
7170 // If the pointer types don't match, insert a bitcast.
7171 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007172 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007173 }
7174
7175 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007176 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007177 }
7178
7179 // The code below only handles extension cast instructions, so far.
7180 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007181 if (LHSCI->getOpcode() != Instruction::ZExt &&
7182 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007183 return 0;
7184
Reid Spencere4d87aa2006-12-23 06:05:41 +00007185 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewycky4a134af2009-10-25 05:20:17 +00007186 bool isSignedCmp = ICI.isSigned();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007187
Reid Spencere4d87aa2006-12-23 06:05:41 +00007188 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007189 // Not an extension from the same type?
7190 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007191 if (RHSCIOp->getType() != LHSCIOp->getType())
7192 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007193
Nick Lewycky4189a532008-01-28 03:48:02 +00007194 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007195 // and the other is a zext), then we can't handle this.
7196 if (CI->getOpcode() != LHSCI->getOpcode())
7197 return 0;
7198
Nick Lewycky4189a532008-01-28 03:48:02 +00007199 // Deal with equality cases early.
7200 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007201 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007202
7203 // A signed comparison of sign extended values simplifies into a
7204 // signed comparison.
7205 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007206 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007207
7208 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007209 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007210 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007211
Reid Spencere4d87aa2006-12-23 06:05:41 +00007212 // If we aren't dealing with a constant on the RHS, exit early
7213 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7214 if (!CI)
7215 return 0;
7216
7217 // Compute the constant that would happen if we truncated to SrcTy then
7218 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007219 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7220 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007221 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007222
7223 // If the re-extended constant didn't change...
7224 if (Res2 == CI) {
7225 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7226 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007227 // %A = sext i16 %X to i32
7228 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007229 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007230 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007231 // because %A may have negative value.
7232 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007233 // However, we allow this when the compare is EQ/NE, because they are
7234 // signless.
7235 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007236 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007237 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007238 }
7239
7240 // The re-extended constant changed so the constant cannot be represented
7241 // in the shorter type. Consequently, we cannot emit a simple comparison.
7242
7243 // First, handle some easy cases. We know the result cannot be equal at this
7244 // point so handle the ICI.isEquality() cases
7245 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007246 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007247 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007248 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007249
7250 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7251 // should have been folded away previously and not enter in here.
7252 Value *Result;
7253 if (isSignedCmp) {
7254 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007255 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007256 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007257 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007258 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007259 } else {
7260 // We're performing an unsigned comparison.
7261 if (isSignedExt) {
7262 // We're performing an unsigned comp with a sign extended value.
7263 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007264 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007265 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007266 } else {
7267 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007268 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007269 }
7270 }
7271
7272 // Finally, return the value computed.
7273 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007274 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007275 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007276
7277 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7278 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7279 "ICmp should be folded!");
7280 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007281 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007282 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007283}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007284
Reid Spencer832254e2007-02-02 02:16:23 +00007285Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7286 return commonShiftTransforms(I);
7287}
7288
7289Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7290 return commonShiftTransforms(I);
7291}
7292
7293Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007294 if (Instruction *R = commonShiftTransforms(I))
7295 return R;
7296
7297 Value *Op0 = I.getOperand(0);
7298
7299 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7300 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7301 if (CSI->isAllOnesValue())
7302 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007303
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007304 // See if we can turn a signed shr into an unsigned shr.
7305 if (MaskedValueIsZero(Op0,
7306 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7307 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7308
7309 // Arithmetic shifting an all-sign-bit value is a no-op.
7310 unsigned NumSignBits = ComputeNumSignBits(Op0);
7311 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7312 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007313
Chris Lattner348f6652007-12-06 01:59:46 +00007314 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007315}
7316
7317Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7318 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007319 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007320
7321 // shl X, 0 == X and shr X, 0 == X
7322 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007323 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7324 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007325 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007326
Reid Spencere4d87aa2006-12-23 06:05:41 +00007327 if (isa<UndefValue>(Op0)) {
7328 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007329 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007330 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007331 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007332 }
7333 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007334 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7335 return ReplaceInstUsesWith(I, Op0);
7336 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007337 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007338 }
7339
Dan Gohman9004c8a2009-05-21 02:28:33 +00007340 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007341 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007342 return &I;
7343
Chris Lattner2eefe512004-04-09 19:05:30 +00007344 // Try to fold constant and into select arguments.
7345 if (isa<Constant>(Op0))
7346 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007347 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007348 return R;
7349
Reid Spencerb83eb642006-10-20 07:07:24 +00007350 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007351 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7352 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007353 return 0;
7354}
7355
Reid Spencerb83eb642006-10-20 07:07:24 +00007356Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007357 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007358 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007359
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007360 // See if we can simplify any instructions used by the instruction whose sole
7361 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007362 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007363
Dan Gohmana119de82009-06-14 23:30:43 +00007364 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7365 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007366 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007367 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007368 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007369 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007370 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007371 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007372 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007373 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007374 }
7375
7376 // ((X*C1) << C2) == (X * (C1 << C2))
7377 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7378 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7379 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007380 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007381 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007382
7383 // Try to fold constant and into select arguments.
7384 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7385 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7386 return R;
7387 if (isa<PHINode>(Op0))
7388 if (Instruction *NV = FoldOpIntoPhi(I))
7389 return NV;
7390
Chris Lattner8999dd32007-12-22 09:07:47 +00007391 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7392 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7393 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7394 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7395 // place. Don't try to do this transformation in this case. Also, we
7396 // require that the input operand is a shift-by-constant so that we have
7397 // confidence that the shifts will get folded together. We could do this
7398 // xform in more cases, but it is unlikely to be profitable.
7399 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7400 isa<ConstantInt>(TrOp->getOperand(1))) {
7401 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007402 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007403 // (shift2 (shift1 & 0x00FF), c2)
7404 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007405
7406 // For logical shifts, the truncation has the effect of making the high
7407 // part of the register be zeros. Emulate this by inserting an AND to
7408 // clear the top bits as needed. This 'and' will usually be zapped by
7409 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007410 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7411 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007412 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7413
7414 // The mask we constructed says what the trunc would do if occurring
7415 // between the shifts. We want to know the effect *after* the second
7416 // shift. We know that it is a logical shift by a constant, so adjust the
7417 // mask as appropriate.
7418 if (I.getOpcode() == Instruction::Shl)
7419 MaskV <<= Op1->getZExtValue();
7420 else {
7421 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7422 MaskV = MaskV.lshr(Op1->getZExtValue());
7423 }
7424
Chris Lattner74381062009-08-30 07:44:24 +00007425 // shift1 & 0x00FF
7426 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7427 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007428
7429 // Return the value truncated to the interesting size.
7430 return new TruncInst(And, I.getType());
7431 }
7432 }
7433
Chris Lattner4d5542c2006-01-06 07:12:35 +00007434 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007435 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7436 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7437 Value *V1, *V2;
7438 ConstantInt *CC;
7439 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007440 default: break;
7441 case Instruction::Add:
7442 case Instruction::And:
7443 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007444 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007445 // These operators commute.
7446 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007447 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007448 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007449 m_Specific(Op1)))) {
7450 Value *YS = // (Y << C)
7451 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7452 // (X + (Y << C))
7453 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7454 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007455 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007456 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007457 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007458 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007459
Chris Lattner150f12a2005-09-18 06:30:59 +00007460 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007461 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007462 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007463 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007464 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007465 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007466 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007467 Value *YS = // (Y << C)
7468 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7469 Op0BO->getName());
7470 // X & (CC << C)
7471 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7472 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007473 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007474 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007475 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007476
Reid Spencera07cb7d2007-02-02 14:41:37 +00007477 // FALL THROUGH.
7478 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007479 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007480 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007481 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007482 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007483 Value *YS = // (Y << C)
7484 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7485 // (X + (Y << C))
7486 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7487 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007488 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007489 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007490 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007491 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007492
Chris Lattner13d4ab42006-05-31 21:14:00 +00007493 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007494 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7495 match(Op0BO->getOperand(0),
7496 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007497 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007498 cast<BinaryOperator>(Op0BO->getOperand(0))
7499 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007500 Value *YS = // (Y << C)
7501 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7502 // X & (CC << C)
7503 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7504 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007505
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007506 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007507 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007508
Chris Lattner11021cb2005-09-18 05:12:10 +00007509 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007510 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007511 }
7512
7513
7514 // If the operand is an bitwise operator with a constant RHS, and the
7515 // shift is the only use, we can pull it out of the shift.
7516 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7517 bool isValid = true; // Valid only for And, Or, Xor
7518 bool highBitSet = false; // Transform if high bit of constant set?
7519
7520 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007521 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007522 case Instruction::Add:
7523 isValid = isLeftShift;
7524 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007525 case Instruction::Or:
7526 case Instruction::Xor:
7527 highBitSet = false;
7528 break;
7529 case Instruction::And:
7530 highBitSet = true;
7531 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007532 }
7533
7534 // If this is a signed shift right, and the high bit is modified
7535 // by the logical operation, do not perform the transformation.
7536 // The highBitSet boolean indicates the value of the high bit of
7537 // the constant which would cause it to be modified for this
7538 // operation.
7539 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007540 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007541 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007542
7543 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007544 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007545
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007546 Value *NewShift =
7547 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007548 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007549
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007550 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007551 NewRHS);
7552 }
7553 }
7554 }
7555 }
7556
Chris Lattnerad0124c2006-01-06 07:52:12 +00007557 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007558 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7559 if (ShiftOp && !ShiftOp->isShift())
7560 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007561
Reid Spencerb83eb642006-10-20 07:07:24 +00007562 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007563 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007564 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7565 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007566 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7567 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7568 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007569
Zhou Sheng4351c642007-04-02 08:20:41 +00007570 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007571
7572 const IntegerType *Ty = cast<IntegerType>(I.getType());
7573
7574 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007575 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007576 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7577 // saturates.
7578 if (AmtSum >= TypeBits) {
7579 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007580 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007581 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7582 }
7583
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007584 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007585 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007586 }
7587
7588 if (ShiftOp->getOpcode() == Instruction::LShr &&
7589 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007590 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007591 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007592
Chris Lattnerb87056f2007-02-05 00:57:54 +00007593 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007594 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007595 }
7596
7597 if (ShiftOp->getOpcode() == Instruction::AShr &&
7598 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007599 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007600 if (AmtSum >= TypeBits)
7601 AmtSum = TypeBits-1;
7602
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007603 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007604
Zhou Shenge9e03f62007-03-28 15:02:20 +00007605 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007606 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007607 }
7608
Chris Lattnerb87056f2007-02-05 00:57:54 +00007609 // Okay, if we get here, one shift must be left, and the other shift must be
7610 // right. See if the amounts are equal.
7611 if (ShiftAmt1 == ShiftAmt2) {
7612 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7613 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007614 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007615 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007616 }
7617 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7618 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007619 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007620 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007621 }
7622 // We can simplify ((X << C) >>s C) into a trunc + sext.
7623 // NOTE: we could do this for any C, but that would make 'unusual' integer
7624 // types. For now, just stick to ones well-supported by the code
7625 // generators.
7626 const Type *SExtType = 0;
7627 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007628 case 1 :
7629 case 8 :
7630 case 16 :
7631 case 32 :
7632 case 64 :
7633 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007634 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007635 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007636 default: break;
7637 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007638 if (SExtType)
7639 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007640 // Otherwise, we can't handle it yet.
7641 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007642 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007643
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007644 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007645 if (I.getOpcode() == Instruction::Shl) {
7646 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7647 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007648 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007649
Reid Spencer55702aa2007-03-25 21:11:44 +00007650 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007651 return BinaryOperator::CreateAnd(Shift,
7652 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007653 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007654
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007655 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007656 if (I.getOpcode() == Instruction::LShr) {
7657 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007658 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007659
Reid Spencerd5e30f02007-03-26 17:18:58 +00007660 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007661 return BinaryOperator::CreateAnd(Shift,
7662 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007663 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007664
7665 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7666 } else {
7667 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007668 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007669
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007670 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007671 if (I.getOpcode() == Instruction::Shl) {
7672 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7673 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007674 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7675 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007676
Reid Spencer55702aa2007-03-25 21:11:44 +00007677 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007678 return BinaryOperator::CreateAnd(Shift,
7679 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007680 }
7681
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007682 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007683 if (I.getOpcode() == Instruction::LShr) {
7684 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007685 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007686
Reid Spencer68d27cf2007-03-26 23:45:51 +00007687 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007688 return BinaryOperator::CreateAnd(Shift,
7689 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007690 }
7691
7692 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007693 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007694 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007695 return 0;
7696}
7697
Chris Lattnera1be5662002-05-02 17:06:02 +00007698
Chris Lattnercfd65102005-10-29 04:36:15 +00007699/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7700/// expression. If so, decompose it, returning some value X, such that Val is
7701/// X*Scale+Offset.
7702///
7703static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007704 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007705 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7706 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007707 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007708 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007709 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007710 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007711 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7712 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7713 if (I->getOpcode() == Instruction::Shl) {
7714 // This is a value scaled by '1 << the shift amt'.
7715 Scale = 1U << RHS->getZExtValue();
7716 Offset = 0;
7717 return I->getOperand(0);
7718 } else if (I->getOpcode() == Instruction::Mul) {
7719 // This value is scaled by 'RHS'.
7720 Scale = RHS->getZExtValue();
7721 Offset = 0;
7722 return I->getOperand(0);
7723 } else if (I->getOpcode() == Instruction::Add) {
7724 // We have X+C. Check to see if we really have (X*C2)+C1,
7725 // where C1 is divisible by C2.
7726 unsigned SubScale;
7727 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007728 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7729 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007730 Offset += RHS->getZExtValue();
7731 Scale = SubScale;
7732 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007733 }
7734 }
7735 }
7736
7737 // Otherwise, we can't look past this.
7738 Scale = 1;
7739 Offset = 0;
7740 return Val;
7741}
7742
7743
Chris Lattnerb3f83972005-10-24 06:03:58 +00007744/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7745/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007746Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00007747 AllocaInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007748 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007749
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007750 BuilderTy AllocaBuilder(*Builder);
7751 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7752
Chris Lattnerb53c2382005-10-24 06:22:12 +00007753 // Remove any uses of AI that are dead.
7754 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007755
Chris Lattnerb53c2382005-10-24 06:22:12 +00007756 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7757 Instruction *User = cast<Instruction>(*UI++);
7758 if (isInstructionTriviallyDead(User)) {
7759 while (UI != E && *UI == User)
7760 ++UI; // If this instruction uses AI more than once, don't break UI.
7761
Chris Lattnerb53c2382005-10-24 06:22:12 +00007762 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007763 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007764 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007765 }
7766 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007767
7768 // This requires TargetData to get the alloca alignment and size information.
7769 if (!TD) return 0;
7770
Chris Lattnerb3f83972005-10-24 06:03:58 +00007771 // Get the type really allocated and the type casted to.
7772 const Type *AllocElTy = AI.getAllocatedType();
7773 const Type *CastElTy = PTy->getElementType();
7774 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007775
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007776 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7777 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007778 if (CastElTyAlign < AllocElTyAlign) return 0;
7779
Chris Lattner39387a52005-10-24 06:35:18 +00007780 // If the allocation has multiple uses, only promote it if we are strictly
7781 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007782 // same, we open the door to infinite loops of various kinds. (A reference
7783 // from a dbg.declare doesn't count as a use for this purpose.)
7784 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7785 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007786
Duncan Sands777d2302009-05-09 07:06:46 +00007787 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7788 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007789 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007790
Chris Lattner455fcc82005-10-29 03:19:53 +00007791 // See if we can satisfy the modulus by pulling a scale out of the array
7792 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007793 unsigned ArraySizeScale;
7794 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007795 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007796 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7797 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007798
Chris Lattner455fcc82005-10-29 03:19:53 +00007799 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7800 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007801 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7802 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007803
Chris Lattner455fcc82005-10-29 03:19:53 +00007804 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7805 Value *Amt = 0;
7806 if (Scale == 1) {
7807 Amt = NumElements;
7808 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007809 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007810 // Insert before the alloca, not before the cast.
7811 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007812 }
7813
Jeff Cohen86796be2007-04-04 16:58:57 +00007814 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007815 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007816 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007817 }
7818
Victor Hernandez7b929da2009-10-23 21:09:37 +00007819 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007820 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007821 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007822
Dale Johannesena0a66372009-03-05 00:39:02 +00007823 // If the allocation has one real use plus a dbg.declare, just remove the
7824 // declare.
7825 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7826 EraseInstFromFunction(*DI);
7827 }
7828 // If the allocation has multiple real uses, insert a cast and change all
7829 // things that used it to use the new cast. This will also hack on CI, but it
7830 // will die soon.
7831 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007832 // New is the allocation instruction, pointer typed. AI is the original
7833 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007834 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007835 AI.replaceAllUsesWith(NewCast);
7836 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007837 return ReplaceInstUsesWith(CI, New);
7838}
7839
Chris Lattner70074e02006-05-13 02:06:03 +00007840/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007841/// and return it as type Ty without inserting any new casts and without
7842/// changing the computed value. This is used by code that tries to decide
7843/// whether promoting or shrinking integer operations to wider or smaller types
7844/// will allow us to eliminate a truncate or extend.
7845///
7846/// This is a truncation operation if Ty is smaller than V->getType(), or an
7847/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007848///
7849/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7850/// should return true if trunc(V) can be computed by computing V in the smaller
7851/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7852/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7853/// efficiently truncated.
7854///
7855/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7856/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7857/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007858bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007859 unsigned CastOpc,
7860 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007861 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007862 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007863 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007864
7865 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007866 if (!I) return false;
7867
Dan Gohman6de29f82009-06-15 22:12:54 +00007868 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007869
Chris Lattner951626b2007-08-02 06:11:14 +00007870 // If this is an extension or truncate, we can often eliminate it.
7871 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7872 // If this is a cast from the destination type, we can trivially eliminate
7873 // it, and this will remove a cast overall.
7874 if (I->getOperand(0)->getType() == Ty) {
7875 // If the first operand is itself a cast, and is eliminable, do not count
7876 // this as an eliminable cast. We would prefer to eliminate those two
7877 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007878 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007879 ++NumCastsRemoved;
7880 return true;
7881 }
7882 }
7883
7884 // We can't extend or shrink something that has multiple uses: doing so would
7885 // require duplicating the instruction in general, which isn't profitable.
7886 if (!I->hasOneUse()) return false;
7887
Evan Chengf35fd542009-01-15 17:01:23 +00007888 unsigned Opc = I->getOpcode();
7889 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007890 case Instruction::Add:
7891 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007892 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007893 case Instruction::And:
7894 case Instruction::Or:
7895 case Instruction::Xor:
7896 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007897 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007898 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007899 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007900 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007901
Eli Friedman070a9812009-07-13 22:46:01 +00007902 case Instruction::UDiv:
7903 case Instruction::URem: {
7904 // UDiv and URem can be truncated if all the truncated bits are zero.
7905 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7906 uint32_t BitWidth = Ty->getScalarSizeInBits();
7907 if (BitWidth < OrigBitWidth) {
7908 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7909 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7910 MaskedValueIsZero(I->getOperand(1), Mask)) {
7911 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7912 NumCastsRemoved) &&
7913 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7914 NumCastsRemoved);
7915 }
7916 }
7917 break;
7918 }
Chris Lattner46b96052006-11-29 07:18:39 +00007919 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007920 // If we are truncating the result of this SHL, and if it's a shift of a
7921 // constant amount, we can always perform a SHL in a smaller type.
7922 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007923 uint32_t BitWidth = Ty->getScalarSizeInBits();
7924 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007925 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007926 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007927 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007928 }
7929 break;
7930 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007931 // If this is a truncate of a logical shr, we can truncate it to a smaller
7932 // lshr iff we know that the bits we would otherwise be shifting in are
7933 // already zeros.
7934 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007935 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7936 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007937 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007938 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007939 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7940 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007941 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007942 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007943 }
7944 }
Chris Lattner46b96052006-11-29 07:18:39 +00007945 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007946 case Instruction::ZExt:
7947 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007948 case Instruction::Trunc:
7949 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007950 // can safely replace it. Note that replacing it does not reduce the number
7951 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007952 if (Opc == CastOpc)
7953 return true;
7954
7955 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007956 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007957 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007958 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007959 case Instruction::Select: {
7960 SelectInst *SI = cast<SelectInst>(I);
7961 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007962 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007963 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007964 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007965 }
Chris Lattner8114b712008-06-18 04:00:49 +00007966 case Instruction::PHI: {
7967 // We can change a phi if we can change all operands.
7968 PHINode *PN = cast<PHINode>(I);
7969 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7970 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007971 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007972 return false;
7973 return true;
7974 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007975 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007976 // TODO: Can handle more cases here.
7977 break;
7978 }
7979
7980 return false;
7981}
7982
7983/// EvaluateInDifferentType - Given an expression that
7984/// CanEvaluateInDifferentType returns true for, actually insert the code to
7985/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007986Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007987 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007988 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007989 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007990 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007991
7992 // Otherwise, it must be an instruction.
7993 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007994 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007995 unsigned Opc = I->getOpcode();
7996 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007997 case Instruction::Add:
7998 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007999 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008000 case Instruction::And:
8001 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008002 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008003 case Instruction::AShr:
8004 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008005 case Instruction::Shl:
8006 case Instruction::UDiv:
8007 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008008 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008009 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008010 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008011 break;
8012 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008013 case Instruction::Trunc:
8014 case Instruction::ZExt:
8015 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008016 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008017 // just return the source. There's no need to insert it because it is not
8018 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008019 if (I->getOperand(0)->getType() == Ty)
8020 return I->getOperand(0);
8021
Chris Lattner8114b712008-06-18 04:00:49 +00008022 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008023 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008024 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008025 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008026 case Instruction::Select: {
8027 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8028 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8029 Res = SelectInst::Create(I->getOperand(0), True, False);
8030 break;
8031 }
Chris Lattner8114b712008-06-18 04:00:49 +00008032 case Instruction::PHI: {
8033 PHINode *OPN = cast<PHINode>(I);
8034 PHINode *NPN = PHINode::Create(Ty);
8035 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8036 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8037 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8038 }
8039 Res = NPN;
8040 break;
8041 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008042 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008043 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008044 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008045 break;
8046 }
8047
Chris Lattner8114b712008-06-18 04:00:49 +00008048 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008049 return InsertNewInstBefore(Res, *I);
8050}
8051
Reid Spencer3da59db2006-11-27 01:05:10 +00008052/// @brief Implement the transforms common to all CastInst visitors.
8053Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008054 Value *Src = CI.getOperand(0);
8055
Dan Gohman23d9d272007-05-11 21:10:54 +00008056 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008057 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008058 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008059 if (Instruction::CastOps opc =
8060 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8061 // The first cast (CSrc) is eliminable so we need to fix up or replace
8062 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008063 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008064 }
8065 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008066
Reid Spencer3da59db2006-11-27 01:05:10 +00008067 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008068 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8069 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8070 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008071
8072 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008073 if (isa<PHINode>(Src))
8074 if (Instruction *NV = FoldOpIntoPhi(CI))
8075 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008076
Reid Spencer3da59db2006-11-27 01:05:10 +00008077 return 0;
8078}
8079
Chris Lattner46cd5a12009-01-09 05:44:56 +00008080/// FindElementAtOffset - Given a type and a constant offset, determine whether
8081/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008082/// the specified offset. If so, fill them into NewIndices and return the
8083/// resultant element type, otherwise return null.
8084static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8085 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008086 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008087 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008088 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008089 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008090
8091 // Start with the index over the outer type. Note that the type size
8092 // might be zero (even if the offset isn't zero) if the indexed type
8093 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008094 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008095 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008096 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008097 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008098 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008099
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008100 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008101 if (Offset < 0) {
8102 --FirstIdx;
8103 Offset += TySize;
8104 assert(Offset >= 0);
8105 }
8106 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8107 }
8108
Owen Andersoneed707b2009-07-24 23:12:02 +00008109 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008110
8111 // Index into the types. If we fail, set OrigBase to null.
8112 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008113 // Indexing into tail padding between struct/array elements.
8114 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008115 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008116
Chris Lattner46cd5a12009-01-09 05:44:56 +00008117 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8118 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008119 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8120 "Offset must stay within the indexed type");
8121
Chris Lattner46cd5a12009-01-09 05:44:56 +00008122 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008123 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008124
8125 Offset -= SL->getElementOffset(Elt);
8126 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008127 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008128 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008129 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008130 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008131 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008132 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008133 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008134 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008135 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008136 }
8137 }
8138
Chris Lattner3914f722009-01-24 01:00:13 +00008139 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008140}
8141
Chris Lattnerd3e28342007-04-27 17:44:50 +00008142/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8143Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8144 Value *Src = CI.getOperand(0);
8145
Chris Lattnerd3e28342007-04-27 17:44:50 +00008146 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008147 // If casting the result of a getelementptr instruction with no offset, turn
8148 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008149 if (GEP->hasAllZeroIndices()) {
8150 // Changing the cast operand is usually not a good idea but it is safe
8151 // here because the pointer operand is being replaced with another
8152 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008153 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008154 CI.setOperand(0, GEP->getOperand(0));
8155 return &CI;
8156 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008157
8158 // If the GEP has a single use, and the base pointer is a bitcast, and the
8159 // GEP computes a constant offset, see if we can convert these three
8160 // instructions into fewer. This typically happens with unions and other
8161 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008162 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008163 if (GEP->hasAllConstantIndices()) {
8164 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008165 ConstantInt *OffsetV =
8166 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008167 int64_t Offset = OffsetV->getSExtValue();
8168
8169 // Get the base pointer input of the bitcast, and the type it points to.
8170 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8171 const Type *GEPIdxTy =
8172 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008173 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008174 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008175 // If we were able to index down into an element, create the GEP
8176 // and bitcast the result. This eliminates one bitcast, potentially
8177 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008178 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8179 Builder->CreateInBoundsGEP(OrigBase,
8180 NewIndices.begin(), NewIndices.end()) :
8181 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008182 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008183
Chris Lattner46cd5a12009-01-09 05:44:56 +00008184 if (isa<BitCastInst>(CI))
8185 return new BitCastInst(NGEP, CI.getType());
8186 assert(isa<PtrToIntInst>(CI));
8187 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008188 }
8189 }
8190 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008191 }
8192
8193 return commonCastTransforms(CI);
8194}
8195
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008196/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8197/// type like i42. We don't want to introduce operations on random non-legal
8198/// integer types where they don't already exist in the code. In the future,
8199/// we should consider making this based off target-data, so that 32-bit targets
8200/// won't get i64 operations etc.
8201static bool isSafeIntegerType(const Type *Ty) {
8202 switch (Ty->getPrimitiveSizeInBits()) {
8203 case 8:
8204 case 16:
8205 case 32:
8206 case 64:
8207 return true;
8208 default:
8209 return false;
8210 }
8211}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008212
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008213/// commonIntCastTransforms - This function implements the common transforms
8214/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008215Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8216 if (Instruction *Result = commonCastTransforms(CI))
8217 return Result;
8218
8219 Value *Src = CI.getOperand(0);
8220 const Type *SrcTy = Src->getType();
8221 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008222 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8223 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008224
Reid Spencer3da59db2006-11-27 01:05:10 +00008225 // See if we can simplify any instructions used by the LHS whose sole
8226 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008227 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008228 return &CI;
8229
8230 // If the source isn't an instruction or has more than one use then we
8231 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008232 Instruction *SrcI = dyn_cast<Instruction>(Src);
8233 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008234 return 0;
8235
Chris Lattnerc739cd62007-03-03 05:27:34 +00008236 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008237 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008238 // Only do this if the dest type is a simple type, don't convert the
8239 // expression tree to something weird like i93 unless the source is also
8240 // strange.
8241 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008242 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8243 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008244 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008245 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008246 // eliminates the cast, so it is always a win. If this is a zero-extension,
8247 // we need to do an AND to maintain the clear top-part of the computation,
8248 // so we require that the input have eliminated at least one cast. If this
8249 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008250 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008251 bool DoXForm = false;
8252 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008253 switch (CI.getOpcode()) {
8254 default:
8255 // All the others use floating point so we shouldn't actually
8256 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008257 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008258 case Instruction::Trunc:
8259 DoXForm = true;
8260 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008261 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008262 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008263 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008264 // If it's unnecessary to issue an AND to clear the high bits, it's
8265 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008266 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008267 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8268 if (MaskedValueIsZero(TryRes, Mask))
8269 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008270
8271 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008272 if (TryI->use_empty())
8273 EraseInstFromFunction(*TryI);
8274 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008275 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008276 }
Evan Chengf35fd542009-01-15 17:01:23 +00008277 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008278 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008279 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008280 // If we do not have to emit the truncate + sext pair, then it's always
8281 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008282 //
8283 // It's not safe to eliminate the trunc + sext pair if one of the
8284 // eliminated cast is a truncate. e.g.
8285 // t2 = trunc i32 t1 to i16
8286 // t3 = sext i16 t2 to i32
8287 // !=
8288 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008289 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008290 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8291 if (NumSignBits > (DestBitSize - SrcBitSize))
8292 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008293
8294 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008295 if (TryI->use_empty())
8296 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008297 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008298 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008299 }
Evan Chengf35fd542009-01-15 17:01:23 +00008300 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008301
8302 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008303 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8304 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008305 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8306 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008307 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008308 // Just replace this cast with the result.
8309 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008310
Reid Spencer3da59db2006-11-27 01:05:10 +00008311 assert(Res->getType() == DestTy);
8312 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008313 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008314 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008315 // Just replace this cast with the result.
8316 return ReplaceInstUsesWith(CI, Res);
8317 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008318 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008319
8320 // If the high bits are already zero, just replace this cast with the
8321 // result.
8322 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8323 if (MaskedValueIsZero(Res, Mask))
8324 return ReplaceInstUsesWith(CI, Res);
8325
8326 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008327 Constant *C = ConstantInt::get(*Context,
8328 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008329 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008330 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008331 case Instruction::SExt: {
8332 // If the high bits are already filled with sign bit, just replace this
8333 // cast with the result.
8334 unsigned NumSignBits = ComputeNumSignBits(Res);
8335 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008336 return ReplaceInstUsesWith(CI, Res);
8337
Reid Spencer3da59db2006-11-27 01:05:10 +00008338 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008339 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008340 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008341 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008342 }
8343 }
8344
8345 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8346 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8347
8348 switch (SrcI->getOpcode()) {
8349 case Instruction::Add:
8350 case Instruction::Mul:
8351 case Instruction::And:
8352 case Instruction::Or:
8353 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008354 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008355 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8356 // Don't insert two casts unless at least one can be eliminated.
8357 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008358 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008359 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8360 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008361 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008362 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008363 }
8364 }
8365
8366 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8367 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8368 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008369 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008370 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008371 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008372 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008373 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008374 }
8375 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008376
Eli Friedman65445c52009-07-13 21:45:57 +00008377 case Instruction::Shl: {
8378 // Canonicalize trunc inside shl, if we can.
8379 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8380 if (CI && DestBitSize < SrcBitSize &&
8381 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008382 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8383 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008384 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008385 }
8386 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008387 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008388 }
8389 return 0;
8390}
8391
Chris Lattner8a9f5712007-04-11 06:57:46 +00008392Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008393 if (Instruction *Result = commonIntCastTransforms(CI))
8394 return Result;
8395
8396 Value *Src = CI.getOperand(0);
8397 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008398 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8399 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008400
8401 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008402 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008403 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008404 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008405 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008406 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008407 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008408
Chris Lattner4f9797d2009-03-24 18:15:30 +00008409 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8410 ConstantInt *ShAmtV = 0;
8411 Value *ShiftOp = 0;
8412 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008413 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008414 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8415
8416 // Get a mask for the bits shifting in.
8417 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8418 if (MaskedValueIsZero(ShiftOp, Mask)) {
8419 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008420 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008421
8422 // Okay, we can shrink this. Truncate the input, then return a new
8423 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008424 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008425 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008426 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008427 }
8428 }
8429
8430 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008431}
8432
Evan Chengb98a10e2008-03-24 00:21:34 +00008433/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8434/// in order to eliminate the icmp.
8435Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8436 bool DoXform) {
8437 // If we are just checking for a icmp eq of a single bit and zext'ing it
8438 // to an integer, then shift the bit to the appropriate place and then
8439 // cast to integer to avoid the comparison.
8440 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8441 const APInt &Op1CV = Op1C->getValue();
8442
8443 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8444 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8445 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8446 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8447 if (!DoXform) return ICI;
8448
8449 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008450 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008451 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008452 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008453 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008454 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008455
8456 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008457 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008458 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008459 }
8460
8461 return ReplaceInstUsesWith(CI, In);
8462 }
8463
8464
8465
8466 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8467 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8468 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8469 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8470 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8471 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8472 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8473 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8474 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8475 // This only works for EQ and NE
8476 ICI->isEquality()) {
8477 // If Op1C some other power of two, convert:
8478 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8479 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8480 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8481 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8482
8483 APInt KnownZeroMask(~KnownZero);
8484 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8485 if (!DoXform) return ICI;
8486
8487 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8488 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8489 // (X&4) == 2 --> false
8490 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008491 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008492 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008493 return ReplaceInstUsesWith(CI, Res);
8494 }
8495
8496 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8497 Value *In = ICI->getOperand(0);
8498 if (ShiftAmt) {
8499 // Perform a logical shr by shiftamt.
8500 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008501 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8502 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008503 }
8504
8505 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008506 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008507 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008508 }
8509
8510 if (CI.getType() == In->getType())
8511 return ReplaceInstUsesWith(CI, In);
8512 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008513 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008514 }
8515 }
8516 }
8517
8518 return 0;
8519}
8520
Chris Lattner8a9f5712007-04-11 06:57:46 +00008521Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008522 // If one of the common conversion will work ..
8523 if (Instruction *Result = commonIntCastTransforms(CI))
8524 return Result;
8525
8526 Value *Src = CI.getOperand(0);
8527
Chris Lattnera84f47c2009-02-17 20:47:23 +00008528 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8529 // types and if the sizes are just right we can convert this into a logical
8530 // 'and' which will be much cheaper than the pair of casts.
8531 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8532 // Get the sizes of the types involved. We know that the intermediate type
8533 // will be smaller than A or C, but don't know the relation between A and C.
8534 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008535 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8536 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8537 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008538 // If we're actually extending zero bits, then if
8539 // SrcSize < DstSize: zext(a & mask)
8540 // SrcSize == DstSize: a & mask
8541 // SrcSize > DstSize: trunc(a) & mask
8542 if (SrcSize < DstSize) {
8543 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008544 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008545 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008546 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008547 }
8548
8549 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008550 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008551 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008552 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008553 }
8554 if (SrcSize > DstSize) {
8555 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008556 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008557 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008558 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008559 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008560 }
8561 }
8562
Evan Chengb98a10e2008-03-24 00:21:34 +00008563 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8564 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008565
Evan Chengb98a10e2008-03-24 00:21:34 +00008566 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8567 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8568 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8569 // of the (zext icmp) will be transformed.
8570 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8571 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8572 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8573 (transformZExtICmp(LHS, CI, false) ||
8574 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008575 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8576 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008577 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008578 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008579 }
8580
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008581 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008582 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8583 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8584 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8585 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008586 if (TI0->getType() == CI.getType())
8587 return
8588 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008589 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008590 }
8591
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008592 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8593 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8594 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8595 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8596 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8597 And->getOperand(1) == C)
8598 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8599 Value *TI0 = TI->getOperand(0);
8600 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008601 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008602 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008603 return BinaryOperator::CreateXor(NewAnd, ZC);
8604 }
8605 }
8606
Reid Spencer3da59db2006-11-27 01:05:10 +00008607 return 0;
8608}
8609
Chris Lattner8a9f5712007-04-11 06:57:46 +00008610Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008611 if (Instruction *I = commonIntCastTransforms(CI))
8612 return I;
8613
Chris Lattner8a9f5712007-04-11 06:57:46 +00008614 Value *Src = CI.getOperand(0);
8615
Dan Gohman1975d032008-10-30 20:40:10 +00008616 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008617 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008618 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008619 Constant::getAllOnesValue(CI.getType()),
8620 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008621
8622 // See if the value being truncated is already sign extended. If so, just
8623 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008624 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008625 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008626 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8627 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8628 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008629 unsigned NumSignBits = ComputeNumSignBits(Op);
8630
8631 if (OpBits == DestBits) {
8632 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8633 // bits, it is already ready.
8634 if (NumSignBits > DestBits-MidBits)
8635 return ReplaceInstUsesWith(CI, Op);
8636 } else if (OpBits < DestBits) {
8637 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8638 // bits, just sext from i32.
8639 if (NumSignBits > OpBits-MidBits)
8640 return new SExtInst(Op, CI.getType(), "tmp");
8641 } else {
8642 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8643 // bits, just truncate to i32.
8644 if (NumSignBits > OpBits-MidBits)
8645 return new TruncInst(Op, CI.getType(), "tmp");
8646 }
8647 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008648
8649 // If the input is a shl/ashr pair of a same constant, then this is a sign
8650 // extension from a smaller value. If we could trust arbitrary bitwidth
8651 // integers, we could turn this into a truncate to the smaller bit and then
8652 // use a sext for the whole extension. Since we don't, look deeper and check
8653 // for a truncate. If the source and dest are the same type, eliminate the
8654 // trunc and extend and just do shifts. For example, turn:
8655 // %a = trunc i32 %i to i8
8656 // %b = shl i8 %a, 6
8657 // %c = ashr i8 %b, 6
8658 // %d = sext i8 %c to i32
8659 // into:
8660 // %a = shl i32 %i, 30
8661 // %d = ashr i32 %a, 30
8662 Value *A = 0;
8663 ConstantInt *BA = 0, *CA = 0;
8664 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008665 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008666 BA == CA && isa<TruncInst>(A)) {
8667 Value *I = cast<TruncInst>(A)->getOperand(0);
8668 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008669 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8670 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008671 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008672 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008673 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008674 return BinaryOperator::CreateAShr(I, ShAmtV);
8675 }
8676 }
8677
Chris Lattnerba417832007-04-11 06:12:58 +00008678 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008679}
8680
Chris Lattnerb7530652008-01-27 05:29:54 +00008681/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8682/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008683static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008684 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008685 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008686 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008687 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8688 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008689 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008690 return 0;
8691}
8692
8693/// LookThroughFPExtensions - If this is an fp extension instruction, look
8694/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008695static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008696 if (Instruction *I = dyn_cast<Instruction>(V))
8697 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008698 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008699
8700 // If this value is a constant, return the constant in the smallest FP type
8701 // that can accurately represent it. This allows us to turn
8702 // (float)((double)X+2.0) into x+2.0f.
8703 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008704 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008705 return V; // No constant folding of this.
8706 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008707 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008708 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008709 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008710 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008711 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008712 return V;
8713 // Don't try to shrink to various long double types.
8714 }
8715
8716 return V;
8717}
8718
8719Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8720 if (Instruction *I = commonCastTransforms(CI))
8721 return I;
8722
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008723 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008724 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008725 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008726 // many builtins (sqrt, etc).
8727 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8728 if (OpI && OpI->hasOneUse()) {
8729 switch (OpI->getOpcode()) {
8730 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008731 case Instruction::FAdd:
8732 case Instruction::FSub:
8733 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008734 case Instruction::FDiv:
8735 case Instruction::FRem:
8736 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008737 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8738 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008739 if (LHSTrunc->getType() != SrcTy &&
8740 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008741 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008742 // If the source types were both smaller than the destination type of
8743 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008744 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8745 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008746 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8747 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008748 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008749 }
8750 }
8751 break;
8752 }
8753 }
8754 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008755}
8756
8757Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8758 return commonCastTransforms(CI);
8759}
8760
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008761Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008762 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8763 if (OpI == 0)
8764 return commonCastTransforms(FI);
8765
8766 // fptoui(uitofp(X)) --> X
8767 // fptoui(sitofp(X)) --> X
8768 // This is safe if the intermediate type has enough bits in its mantissa to
8769 // accurately represent all values of X. For example, do not do this with
8770 // i64->float->i64. This is also safe for sitofp case, because any negative
8771 // 'X' value would cause an undefined result for the fptoui.
8772 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8773 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008774 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008775 OpI->getType()->getFPMantissaWidth())
8776 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008777
8778 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008779}
8780
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008781Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008782 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8783 if (OpI == 0)
8784 return commonCastTransforms(FI);
8785
8786 // fptosi(sitofp(X)) --> X
8787 // fptosi(uitofp(X)) --> X
8788 // This is safe if the intermediate type has enough bits in its mantissa to
8789 // accurately represent all values of X. For example, do not do this with
8790 // i64->float->i64. This is also safe for sitofp case, because any negative
8791 // 'X' value would cause an undefined result for the fptoui.
8792 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8793 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008794 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008795 OpI->getType()->getFPMantissaWidth())
8796 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008797
8798 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008799}
8800
8801Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8802 return commonCastTransforms(CI);
8803}
8804
8805Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8806 return commonCastTransforms(CI);
8807}
8808
Chris Lattnera0e69692009-03-24 18:35:40 +00008809Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8810 // If the destination integer type is smaller than the intptr_t type for
8811 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8812 // trunc to be exposed to other transforms. Don't do this for extending
8813 // ptrtoint's, because we don't know if the target sign or zero extends its
8814 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008815 if (TD &&
8816 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008817 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8818 TD->getIntPtrType(CI.getContext()),
8819 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008820 return new TruncInst(P, CI.getType());
8821 }
8822
Chris Lattnerd3e28342007-04-27 17:44:50 +00008823 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008824}
8825
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008826Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008827 // If the source integer type is larger than the intptr_t type for
8828 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8829 // allows the trunc to be exposed to other transforms. Don't do this for
8830 // extending inttoptr's, because we don't know if the target sign or zero
8831 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008832 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008833 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008834 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8835 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008836 return new IntToPtrInst(P, CI.getType());
8837 }
8838
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008839 if (Instruction *I = commonCastTransforms(CI))
8840 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008841
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008842 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008843}
8844
Chris Lattnerd3e28342007-04-27 17:44:50 +00008845Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008846 // If the operands are integer typed then apply the integer transforms,
8847 // otherwise just apply the common ones.
8848 Value *Src = CI.getOperand(0);
8849 const Type *SrcTy = Src->getType();
8850 const Type *DestTy = CI.getType();
8851
Eli Friedman7e25d452009-07-13 20:53:00 +00008852 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008853 if (Instruction *I = commonPointerCastTransforms(CI))
8854 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008855 } else {
8856 if (Instruction *Result = commonCastTransforms(CI))
8857 return Result;
8858 }
8859
8860
8861 // Get rid of casts from one type to the same type. These are useless and can
8862 // be replaced by the operand.
8863 if (DestTy == Src->getType())
8864 return ReplaceInstUsesWith(CI, Src);
8865
Reid Spencer3da59db2006-11-27 01:05:10 +00008866 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008867 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8868 const Type *DstElTy = DstPTy->getElementType();
8869 const Type *SrcElTy = SrcPTy->getElementType();
8870
Nate Begeman83ad90a2008-03-31 00:22:16 +00008871 // If the address spaces don't match, don't eliminate the bitcast, which is
8872 // required for changing types.
8873 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8874 return 0;
8875
Victor Hernandez83d63912009-09-18 22:35:49 +00008876 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00008877 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00008878 // There is no need to modify malloc calls because it is their bitcast that
8879 // needs to be cleaned up.
Victor Hernandez7b929da2009-10-23 21:09:37 +00008880 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Chris Lattnerd3e28342007-04-27 17:44:50 +00008881 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8882 return V;
8883
Chris Lattnerd717c182007-05-05 22:32:24 +00008884 // If the source and destination are pointers, and this cast is equivalent
8885 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008886 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008887 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008888 unsigned NumZeros = 0;
8889 while (SrcElTy != DstElTy &&
8890 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8891 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8892 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8893 ++NumZeros;
8894 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008895
Chris Lattnerd3e28342007-04-27 17:44:50 +00008896 // If we found a path from the src to dest, create the getelementptr now.
8897 if (SrcElTy == DstElTy) {
8898 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008899 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8900 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008901 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008902 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008903
Eli Friedman2451a642009-07-18 23:06:53 +00008904 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8905 if (DestVTy->getNumElements() == 1) {
8906 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008907 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008908 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00008909 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008910 }
8911 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8912 }
8913 }
8914
8915 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8916 if (SrcVTy->getNumElements() == 1) {
8917 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008918 Value *Elem =
8919 Builder->CreateExtractElement(Src,
8920 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008921 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8922 }
8923 }
8924 }
8925
Reid Spencer3da59db2006-11-27 01:05:10 +00008926 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8927 if (SVI->hasOneUse()) {
8928 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8929 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008930 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008931 cast<VectorType>(DestTy)->getNumElements() ==
8932 SVI->getType()->getNumElements() &&
8933 SVI->getType()->getNumElements() ==
8934 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008935 CastInst *Tmp;
8936 // If either of the operands is a cast from CI.getType(), then
8937 // evaluating the shuffle in the casted destination's type will allow
8938 // us to eliminate at least one cast.
8939 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8940 Tmp->getOperand(0)->getType() == DestTy) ||
8941 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8942 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008943 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8944 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008945 // Return a new shuffle vector. Use the same element ID's, as we
8946 // know the vector types match #elts.
8947 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008948 }
8949 }
8950 }
8951 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008952 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008953}
8954
Chris Lattnere576b912004-04-09 23:46:01 +00008955/// GetSelectFoldableOperands - We want to turn code that looks like this:
8956/// %C = or %A, %B
8957/// %D = select %cond, %C, %A
8958/// into:
8959/// %C = select %cond, %B, 0
8960/// %D = or %A, %C
8961///
8962/// Assuming that the specified instruction is an operand to the select, return
8963/// a bitmask indicating which operands of this instruction are foldable if they
8964/// equal the other incoming value of the select.
8965///
8966static unsigned GetSelectFoldableOperands(Instruction *I) {
8967 switch (I->getOpcode()) {
8968 case Instruction::Add:
8969 case Instruction::Mul:
8970 case Instruction::And:
8971 case Instruction::Or:
8972 case Instruction::Xor:
8973 return 3; // Can fold through either operand.
8974 case Instruction::Sub: // Can only fold on the amount subtracted.
8975 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008976 case Instruction::LShr:
8977 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008978 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008979 default:
8980 return 0; // Cannot fold
8981 }
8982}
8983
8984/// GetSelectFoldableConstant - For the same transformation as the previous
8985/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00008986static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008987 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00008988 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008989 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00008990 case Instruction::Add:
8991 case Instruction::Sub:
8992 case Instruction::Or:
8993 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008994 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008995 case Instruction::LShr:
8996 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00008997 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008998 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00008999 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009000 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009001 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009002 }
9003}
9004
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009005/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9006/// have the same opcode and only one use each. Try to simplify this.
9007Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9008 Instruction *FI) {
9009 if (TI->getNumOperands() == 1) {
9010 // If this is a non-volatile load or a cast from the same type,
9011 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009012 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009013 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9014 return 0;
9015 } else {
9016 return 0; // unknown unary op.
9017 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009018
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009019 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009020 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009021 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009022 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009023 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009024 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009025 }
9026
Reid Spencer832254e2007-02-02 02:16:23 +00009027 // Only handle binary operators here.
9028 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009029 return 0;
9030
9031 // Figure out if the operations have any operands in common.
9032 Value *MatchOp, *OtherOpT, *OtherOpF;
9033 bool MatchIsOpZero;
9034 if (TI->getOperand(0) == FI->getOperand(0)) {
9035 MatchOp = TI->getOperand(0);
9036 OtherOpT = TI->getOperand(1);
9037 OtherOpF = FI->getOperand(1);
9038 MatchIsOpZero = true;
9039 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9040 MatchOp = TI->getOperand(1);
9041 OtherOpT = TI->getOperand(0);
9042 OtherOpF = FI->getOperand(0);
9043 MatchIsOpZero = false;
9044 } else if (!TI->isCommutative()) {
9045 return 0;
9046 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9047 MatchOp = TI->getOperand(0);
9048 OtherOpT = TI->getOperand(1);
9049 OtherOpF = FI->getOperand(0);
9050 MatchIsOpZero = true;
9051 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9052 MatchOp = TI->getOperand(1);
9053 OtherOpT = TI->getOperand(0);
9054 OtherOpF = FI->getOperand(1);
9055 MatchIsOpZero = true;
9056 } else {
9057 return 0;
9058 }
9059
9060 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009061 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9062 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009063 InsertNewInstBefore(NewSI, SI);
9064
9065 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9066 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009067 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009068 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009069 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009070 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009071 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009072 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009073}
9074
Evan Chengde621922009-03-31 20:42:45 +00009075static bool isSelect01(Constant *C1, Constant *C2) {
9076 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9077 if (!C1I)
9078 return false;
9079 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9080 if (!C2I)
9081 return false;
9082 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9083}
9084
9085/// FoldSelectIntoOp - Try fold the select into one of the operands to
9086/// facilitate further optimization.
9087Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9088 Value *FalseVal) {
9089 // See the comment above GetSelectFoldableOperands for a description of the
9090 // transformation we are doing here.
9091 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9092 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9093 !isa<Constant>(FalseVal)) {
9094 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9095 unsigned OpToFold = 0;
9096 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9097 OpToFold = 1;
9098 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9099 OpToFold = 2;
9100 }
9101
9102 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009103 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009104 Value *OOp = TVI->getOperand(2-OpToFold);
9105 // Avoid creating select between 2 constants unless it's selecting
9106 // between 0 and 1.
9107 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9108 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9109 InsertNewInstBefore(NewSel, SI);
9110 NewSel->takeName(TVI);
9111 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9112 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009113 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009114 }
9115 }
9116 }
9117 }
9118 }
9119
9120 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9121 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9122 !isa<Constant>(TrueVal)) {
9123 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9124 unsigned OpToFold = 0;
9125 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9126 OpToFold = 1;
9127 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9128 OpToFold = 2;
9129 }
9130
9131 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009132 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009133 Value *OOp = FVI->getOperand(2-OpToFold);
9134 // Avoid creating select between 2 constants unless it's selecting
9135 // between 0 and 1.
9136 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9137 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9138 InsertNewInstBefore(NewSel, SI);
9139 NewSel->takeName(FVI);
9140 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9141 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009142 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009143 }
9144 }
9145 }
9146 }
9147 }
9148
9149 return 0;
9150}
9151
Dan Gohman81b28ce2008-09-16 18:46:06 +00009152/// visitSelectInstWithICmp - Visit a SelectInst that has an
9153/// ICmpInst as its first operand.
9154///
9155Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9156 ICmpInst *ICI) {
9157 bool Changed = false;
9158 ICmpInst::Predicate Pred = ICI->getPredicate();
9159 Value *CmpLHS = ICI->getOperand(0);
9160 Value *CmpRHS = ICI->getOperand(1);
9161 Value *TrueVal = SI.getTrueValue();
9162 Value *FalseVal = SI.getFalseValue();
9163
9164 // Check cases where the comparison is with a constant that
9165 // can be adjusted to fit the min/max idiom. We may edit ICI in
9166 // place here, so make sure the select is the only user.
9167 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009168 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009169 switch (Pred) {
9170 default: break;
9171 case ICmpInst::ICMP_ULT:
9172 case ICmpInst::ICMP_SLT: {
9173 // X < MIN ? T : F --> F
9174 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9175 return ReplaceInstUsesWith(SI, FalseVal);
9176 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009177 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009178 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9179 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9180 Pred = ICmpInst::getSwappedPredicate(Pred);
9181 CmpRHS = AdjustedRHS;
9182 std::swap(FalseVal, TrueVal);
9183 ICI->setPredicate(Pred);
9184 ICI->setOperand(1, CmpRHS);
9185 SI.setOperand(1, TrueVal);
9186 SI.setOperand(2, FalseVal);
9187 Changed = true;
9188 }
9189 break;
9190 }
9191 case ICmpInst::ICMP_UGT:
9192 case ICmpInst::ICMP_SGT: {
9193 // X > MAX ? T : F --> F
9194 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9195 return ReplaceInstUsesWith(SI, FalseVal);
9196 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009197 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009198 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9199 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9200 Pred = ICmpInst::getSwappedPredicate(Pred);
9201 CmpRHS = AdjustedRHS;
9202 std::swap(FalseVal, TrueVal);
9203 ICI->setPredicate(Pred);
9204 ICI->setOperand(1, CmpRHS);
9205 SI.setOperand(1, TrueVal);
9206 SI.setOperand(2, FalseVal);
9207 Changed = true;
9208 }
9209 break;
9210 }
9211 }
9212
Dan Gohman1975d032008-10-30 20:40:10 +00009213 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9214 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009215 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009216 if (match(TrueVal, m_ConstantInt<-1>()) &&
9217 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009218 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009219 else if (match(TrueVal, m_ConstantInt<0>()) &&
9220 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009221 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9222
Dan Gohman1975d032008-10-30 20:40:10 +00009223 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9224 // If we are just checking for a icmp eq of a single bit and zext'ing it
9225 // to an integer, then shift the bit to the appropriate place and then
9226 // cast to integer to avoid the comparison.
9227 const APInt &Op1CV = CI->getValue();
9228
9229 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9230 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9231 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009232 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009233 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009234 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009235 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009236 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009237 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009238 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009239 if (In->getType() != SI.getType())
9240 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009241 true/*SExt*/, "tmp", ICI);
9242
9243 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009244 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009245 In->getName()+".not"), *ICI);
9246
9247 return ReplaceInstUsesWith(SI, In);
9248 }
9249 }
9250 }
9251
Dan Gohman81b28ce2008-09-16 18:46:06 +00009252 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9253 // Transform (X == Y) ? X : Y -> Y
9254 if (Pred == ICmpInst::ICMP_EQ)
9255 return ReplaceInstUsesWith(SI, FalseVal);
9256 // Transform (X != Y) ? X : Y -> X
9257 if (Pred == ICmpInst::ICMP_NE)
9258 return ReplaceInstUsesWith(SI, TrueVal);
9259 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9260
9261 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9262 // Transform (X == Y) ? Y : X -> X
9263 if (Pred == ICmpInst::ICMP_EQ)
9264 return ReplaceInstUsesWith(SI, FalseVal);
9265 // Transform (X != Y) ? Y : X -> Y
9266 if (Pred == ICmpInst::ICMP_NE)
9267 return ReplaceInstUsesWith(SI, TrueVal);
9268 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9269 }
9270
9271 /// NOTE: if we wanted to, this is where to detect integer ABS
9272
9273 return Changed ? &SI : 0;
9274}
9275
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009276
Chris Lattner7f239582009-10-22 00:17:26 +00009277/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9278/// PHI node (but the two may be in different blocks). See if the true/false
9279/// values (V) are live in all of the predecessor blocks of the PHI. For
9280/// example, cases like this cannot be mapped:
9281///
9282/// X = phi [ C1, BB1], [C2, BB2]
9283/// Y = add
9284/// Z = select X, Y, 0
9285///
9286/// because Y is not live in BB1/BB2.
9287///
9288static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9289 const SelectInst &SI) {
9290 // If the value is a non-instruction value like a constant or argument, it
9291 // can always be mapped.
9292 const Instruction *I = dyn_cast<Instruction>(V);
9293 if (I == 0) return true;
9294
9295 // If V is a PHI node defined in the same block as the condition PHI, we can
9296 // map the arguments.
9297 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9298
9299 if (const PHINode *VP = dyn_cast<PHINode>(I))
9300 if (VP->getParent() == CondPHI->getParent())
9301 return true;
9302
9303 // Otherwise, if the PHI and select are defined in the same block and if V is
9304 // defined in a different block, then we can transform it.
9305 if (SI.getParent() == CondPHI->getParent() &&
9306 I->getParent() != CondPHI->getParent())
9307 return true;
9308
9309 // Otherwise we have a 'hard' case and we can't tell without doing more
9310 // detailed dominator based analysis, punt.
9311 return false;
9312}
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009313
Chris Lattner3d69f462004-03-12 05:52:32 +00009314Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009315 Value *CondVal = SI.getCondition();
9316 Value *TrueVal = SI.getTrueValue();
9317 Value *FalseVal = SI.getFalseValue();
9318
9319 // select true, X, Y -> X
9320 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009321 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009322 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009323
9324 // select C, X, X -> X
9325 if (TrueVal == FalseVal)
9326 return ReplaceInstUsesWith(SI, TrueVal);
9327
Chris Lattnere87597f2004-10-16 18:11:37 +00009328 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9329 return ReplaceInstUsesWith(SI, FalseVal);
9330 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9331 return ReplaceInstUsesWith(SI, TrueVal);
9332 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9333 if (isa<Constant>(TrueVal))
9334 return ReplaceInstUsesWith(SI, TrueVal);
9335 else
9336 return ReplaceInstUsesWith(SI, FalseVal);
9337 }
9338
Owen Anderson1d0be152009-08-13 21:58:54 +00009339 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009340 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009341 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009342 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009343 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009344 } else {
9345 // Change: A = select B, false, C --> A = and !B, C
9346 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009347 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009348 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009349 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009350 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009351 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009352 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009353 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009354 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009355 } else {
9356 // Change: A = select B, C, true --> A = or !B, C
9357 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009358 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009359 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009360 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009361 }
9362 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009363
9364 // select a, b, a -> a&b
9365 // select a, a, b -> a|b
9366 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009367 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009368 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009369 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009370 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009371
Chris Lattner2eefe512004-04-09 19:05:30 +00009372 // Selecting between two integer constants?
9373 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9374 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009375 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009376 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009377 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009378 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009379 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009380 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009381 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009382 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009383 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009384 }
Chris Lattner457dd822004-06-09 07:59:58 +00009385
Reid Spencere4d87aa2006-12-23 06:05:41 +00009386 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009387 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009388 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009389 // non-constant value, eliminate this whole mess. This corresponds to
9390 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009391 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009392 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009393 cast<Constant>(IC->getOperand(1))->isNullValue())
9394 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9395 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009396 isa<ConstantInt>(ICA->getOperand(1)) &&
9397 (ICA->getOperand(1) == TrueValC ||
9398 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009399 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9400 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009401 // know whether we have a icmp_ne or icmp_eq and whether the
9402 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009403 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009404 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009405 Value *V = ICA;
9406 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009407 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009408 Instruction::Xor, V, ICA->getOperand(1)), SI);
9409 return ReplaceInstUsesWith(SI, V);
9410 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009411 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009412 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009413
9414 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009415 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9416 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009417 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009418 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9419 // This is not safe in general for floating point:
9420 // consider X== -0, Y== +0.
9421 // It becomes safe if either operand is a nonzero constant.
9422 ConstantFP *CFPt, *CFPf;
9423 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9424 !CFPt->getValueAPF().isZero()) ||
9425 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9426 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009427 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009428 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009429 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009430 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009431 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009432 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009433
Reid Spencere4d87aa2006-12-23 06:05:41 +00009434 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009435 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009436 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9437 // This is not safe in general for floating point:
9438 // consider X== -0, Y== +0.
9439 // It becomes safe if either operand is a nonzero constant.
9440 ConstantFP *CFPt, *CFPf;
9441 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9442 !CFPt->getValueAPF().isZero()) ||
9443 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9444 !CFPf->getValueAPF().isZero()))
9445 return ReplaceInstUsesWith(SI, FalseVal);
9446 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009447 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009448 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9449 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009450 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009451 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009452 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009453 }
9454
9455 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009456 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9457 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9458 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009459
Chris Lattner87875da2005-01-13 22:52:24 +00009460 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9461 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9462 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009463 Instruction *AddOp = 0, *SubOp = 0;
9464
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009465 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9466 if (TI->getOpcode() == FI->getOpcode())
9467 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9468 return IV;
9469
9470 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9471 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009472 if ((TI->getOpcode() == Instruction::Sub &&
9473 FI->getOpcode() == Instruction::Add) ||
9474 (TI->getOpcode() == Instruction::FSub &&
9475 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009476 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009477 } else if ((FI->getOpcode() == Instruction::Sub &&
9478 TI->getOpcode() == Instruction::Add) ||
9479 (FI->getOpcode() == Instruction::FSub &&
9480 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009481 AddOp = TI; SubOp = FI;
9482 }
9483
9484 if (AddOp) {
9485 Value *OtherAddOp = 0;
9486 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9487 OtherAddOp = AddOp->getOperand(1);
9488 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9489 OtherAddOp = AddOp->getOperand(0);
9490 }
9491
9492 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009493 // So at this point we know we have (Y -> OtherAddOp):
9494 // select C, (add X, Y), (sub X, Z)
9495 Value *NegVal; // Compute -Z
9496 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009497 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009498 } else {
9499 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009500 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009501 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009502 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009503
9504 Value *NewTrueOp = OtherAddOp;
9505 Value *NewFalseOp = NegVal;
9506 if (AddOp != TI)
9507 std::swap(NewTrueOp, NewFalseOp);
9508 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009509 SelectInst::Create(CondVal, NewTrueOp,
9510 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009511
9512 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009513 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009514 }
9515 }
9516 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009517
Chris Lattnere576b912004-04-09 23:46:01 +00009518 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009519 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009520 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9521 if (FoldI)
9522 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009523 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009524
Chris Lattner7f239582009-10-22 00:17:26 +00009525 // See if we can fold the select into a phi node if the condition is a select.
9526 if (isa<PHINode>(SI.getCondition()))
9527 // The true/false values have to be live in the PHI predecessor's blocks.
9528 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9529 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9530 if (Instruction *NV = FoldOpIntoPhi(SI))
9531 return NV;
Chris Lattner5d1704d2009-09-27 19:57:57 +00009532
Chris Lattnera1df33c2005-04-24 07:30:14 +00009533 if (BinaryOperator::isNot(CondVal)) {
9534 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9535 SI.setOperand(1, FalseVal);
9536 SI.setOperand(2, TrueVal);
9537 return &SI;
9538 }
9539
Chris Lattner3d69f462004-03-12 05:52:32 +00009540 return 0;
9541}
9542
Dan Gohmaneee962e2008-04-10 18:43:06 +00009543/// EnforceKnownAlignment - If the specified pointer points to an object that
9544/// we control, modify the object's alignment to PrefAlign. This isn't
9545/// often possible though. If alignment is important, a more reliable approach
9546/// is to simply align all global variables and allocation instructions to
9547/// their preferred alignment from the beginning.
9548///
9549static unsigned EnforceKnownAlignment(Value *V,
9550 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009551
Dan Gohmaneee962e2008-04-10 18:43:06 +00009552 User *U = dyn_cast<User>(V);
9553 if (!U) return Align;
9554
Dan Gohmanca178902009-07-17 20:47:02 +00009555 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009556 default: break;
9557 case Instruction::BitCast:
9558 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9559 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009560 // If all indexes are zero, it is just the alignment of the base pointer.
9561 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009562 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009563 if (!isa<Constant>(*i) ||
9564 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009565 AllZeroOperands = false;
9566 break;
9567 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009568
9569 if (AllZeroOperands) {
9570 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009571 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009572 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009573 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009574 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009575 }
9576
9577 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9578 // If there is a large requested alignment and we can, bump up the alignment
9579 // of the global.
9580 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009581 if (GV->getAlignment() >= PrefAlign)
9582 Align = GV->getAlignment();
9583 else {
9584 GV->setAlignment(PrefAlign);
9585 Align = PrefAlign;
9586 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009587 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00009588 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9589 // If there is a requested alignment and if this is an alloca, round up.
9590 if (AI->getAlignment() >= PrefAlign)
9591 Align = AI->getAlignment();
9592 else {
9593 AI->setAlignment(PrefAlign);
9594 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00009595 }
9596 }
9597
9598 return Align;
9599}
9600
9601/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9602/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9603/// and it is more than the alignment of the ultimate object, see if we can
9604/// increase the alignment of the ultimate object, making this check succeed.
9605unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9606 unsigned PrefAlign) {
9607 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9608 sizeof(PrefAlign) * CHAR_BIT;
9609 APInt Mask = APInt::getAllOnesValue(BitWidth);
9610 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9611 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9612 unsigned TrailZ = KnownZero.countTrailingOnes();
9613 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9614
9615 if (PrefAlign > Align)
9616 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9617
9618 // We don't need to make any adjustment.
9619 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009620}
9621
Chris Lattnerf497b022008-01-13 23:50:23 +00009622Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009623 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009624 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009625 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009626 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009627
9628 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009629 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009630 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009631 return MI;
9632 }
9633
9634 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9635 // load/store.
9636 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9637 if (MemOpLength == 0) return 0;
9638
Chris Lattner37ac6082008-01-14 00:28:35 +00009639 // Source and destination pointer types are always "i8*" for intrinsic. See
9640 // if the size is something we can handle with a single primitive load/store.
9641 // A single load+store correctly handles overlapping memory in the memmove
9642 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009643 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009644 if (Size == 0) return MI; // Delete this mem transfer.
9645
9646 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009647 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009648
Chris Lattner37ac6082008-01-14 00:28:35 +00009649 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009650 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009651 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009652
9653 // Memcpy forces the use of i8* for the source and destination. That means
9654 // that if you're using memcpy to move one double around, you'll get a cast
9655 // from double* to i8*. We'd much rather use a double load+store rather than
9656 // an i64 load+store, here because this improves the odds that the source or
9657 // dest address will be promotable. See if we can find a better type than the
9658 // integer datatype.
9659 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9660 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009661 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009662 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9663 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009664 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009665 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9666 if (STy->getNumElements() == 1)
9667 SrcETy = STy->getElementType(0);
9668 else
9669 break;
9670 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9671 if (ATy->getNumElements() == 1)
9672 SrcETy = ATy->getElementType();
9673 else
9674 break;
9675 } else
9676 break;
9677 }
9678
Dan Gohman8f8e2692008-05-23 01:52:21 +00009679 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009680 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009681 }
9682 }
9683
9684
Chris Lattnerf497b022008-01-13 23:50:23 +00009685 // If the memcpy/memmove provides better alignment info than we can
9686 // infer, use it.
9687 SrcAlign = std::max(SrcAlign, CopyAlign);
9688 DstAlign = std::max(DstAlign, CopyAlign);
9689
Chris Lattner08142f22009-08-30 19:47:22 +00009690 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9691 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009692 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9693 InsertNewInstBefore(L, *MI);
9694 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9695
9696 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009697 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009698 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009699}
Chris Lattner3d69f462004-03-12 05:52:32 +00009700
Chris Lattner69ea9d22008-04-30 06:39:11 +00009701Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9702 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009703 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009704 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009705 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009706 return MI;
9707 }
9708
9709 // Extract the length and alignment and fill if they are constant.
9710 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9711 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009712 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009713 return 0;
9714 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009715 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009716
9717 // If the length is zero, this is a no-op
9718 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9719
9720 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9721 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009722 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009723
9724 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009725 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009726
9727 // Alignment 0 is identity for alignment 1 for memset, but not store.
9728 if (Alignment == 0) Alignment = 1;
9729
9730 // Extract the fill value and store.
9731 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009732 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009733 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009734
9735 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009736 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009737 return MI;
9738 }
9739
9740 return 0;
9741}
9742
9743
Chris Lattner8b0ea312006-01-13 20:11:04 +00009744/// visitCallInst - CallInst simplification. This mostly only handles folding
9745/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9746/// the heavy lifting.
9747///
Chris Lattner9fe38862003-06-19 17:00:31 +00009748Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +00009749 if (isFreeCall(&CI))
9750 return visitFree(CI);
9751
Chris Lattneraab6ec42009-05-13 17:39:14 +00009752 // If the caller function is nounwind, mark the call as nounwind, even if the
9753 // callee isn't.
9754 if (CI.getParent()->getParent()->doesNotThrow() &&
9755 !CI.doesNotThrow()) {
9756 CI.setDoesNotThrow();
9757 return &CI;
9758 }
9759
Chris Lattner8b0ea312006-01-13 20:11:04 +00009760 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9761 if (!II) return visitCallSite(&CI);
9762
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009763 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9764 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009765 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009766 bool Changed = false;
9767
9768 // memmove/cpy/set of zero bytes is a noop.
9769 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9770 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9771
Chris Lattner35b9e482004-10-12 04:52:52 +00009772 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009773 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009774 // Replace the instruction with just byte operations. We would
9775 // transform other cases to loads/stores, but we don't know if
9776 // alignment is sufficient.
9777 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009778 }
9779
Chris Lattner35b9e482004-10-12 04:52:52 +00009780 // If we have a memmove and the source operation is a constant global,
9781 // then the source and dest pointers can't alias, so we can change this
9782 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009783 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009784 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9785 if (GVSrc->isConstant()) {
9786 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009787 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9788 const Type *Tys[1];
9789 Tys[0] = CI.getOperand(3)->getType();
9790 CI.setOperand(0,
9791 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009792 Changed = true;
9793 }
Chris Lattnera935db82008-05-28 05:30:41 +00009794
9795 // memmove(x,x,size) -> noop.
9796 if (MMI->getSource() == MMI->getDest())
9797 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009798 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009799
Chris Lattner95a959d2006-03-06 20:18:44 +00009800 // If we can determine a pointer alignment that is bigger than currently
9801 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009802 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009803 if (Instruction *I = SimplifyMemTransfer(MI))
9804 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009805 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9806 if (Instruction *I = SimplifyMemSet(MSI))
9807 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009808 }
9809
Chris Lattner8b0ea312006-01-13 20:11:04 +00009810 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009811 }
9812
9813 switch (II->getIntrinsicID()) {
9814 default: break;
9815 case Intrinsic::bswap:
9816 // bswap(bswap(x)) -> x
9817 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9818 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9819 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9820 break;
9821 case Intrinsic::ppc_altivec_lvx:
9822 case Intrinsic::ppc_altivec_lvxl:
9823 case Intrinsic::x86_sse_loadu_ps:
9824 case Intrinsic::x86_sse2_loadu_pd:
9825 case Intrinsic::x86_sse2_loadu_dq:
9826 // Turn PPC lvx -> load if the pointer is known aligned.
9827 // Turn X86 loadups -> load if the pointer is known aligned.
9828 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00009829 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9830 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00009831 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009832 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009833 break;
9834 case Intrinsic::ppc_altivec_stvx:
9835 case Intrinsic::ppc_altivec_stvxl:
9836 // Turn stvx -> store if the pointer is known aligned.
9837 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9838 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009839 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009840 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009841 return new StoreInst(II->getOperand(1), Ptr);
9842 }
9843 break;
9844 case Intrinsic::x86_sse_storeu_ps:
9845 case Intrinsic::x86_sse2_storeu_pd:
9846 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009847 // Turn X86 storeu -> store if the pointer is known aligned.
9848 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9849 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009850 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009851 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009852 return new StoreInst(II->getOperand(2), Ptr);
9853 }
9854 break;
9855
9856 case Intrinsic::x86_sse_cvttss2si: {
9857 // These intrinsics only demands the 0th element of its input vector. If
9858 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009859 unsigned VWidth =
9860 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9861 APInt DemandedElts(VWidth, 1);
9862 APInt UndefElts(VWidth, 0);
9863 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009864 UndefElts)) {
9865 II->setOperand(1, V);
9866 return II;
9867 }
9868 break;
9869 }
9870
9871 case Intrinsic::ppc_altivec_vperm:
9872 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9873 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9874 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009875
Chris Lattner0521e3c2008-06-18 04:33:20 +00009876 // Check that all of the elements are integer constants or undefs.
9877 bool AllEltsOk = true;
9878 for (unsigned i = 0; i != 16; ++i) {
9879 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9880 !isa<UndefValue>(Mask->getOperand(i))) {
9881 AllEltsOk = false;
9882 break;
9883 }
9884 }
9885
9886 if (AllEltsOk) {
9887 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00009888 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9889 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009890 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009891
Chris Lattner0521e3c2008-06-18 04:33:20 +00009892 // Only extract each element once.
9893 Value *ExtractedElts[32];
9894 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9895
Chris Lattnere2ed0572006-04-06 19:19:17 +00009896 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009897 if (isa<UndefValue>(Mask->getOperand(i)))
9898 continue;
9899 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9900 Idx &= 31; // Match the hardware behavior.
9901
9902 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009903 ExtractedElts[Idx] =
9904 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9905 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9906 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009907 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009908
Chris Lattner0521e3c2008-06-18 04:33:20 +00009909 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009910 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9911 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9912 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009913 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009914 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009915 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009916 }
9917 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009918
Chris Lattner0521e3c2008-06-18 04:33:20 +00009919 case Intrinsic::stackrestore: {
9920 // If the save is right next to the restore, remove the restore. This can
9921 // happen when variable allocas are DCE'd.
9922 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9923 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9924 BasicBlock::iterator BI = SS;
9925 if (&*++BI == II)
9926 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009927 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009928 }
9929
9930 // Scan down this block to see if there is another stack restore in the
9931 // same block without an intervening call/alloca.
9932 BasicBlock::iterator BI = II;
9933 TerminatorInst *TI = II->getParent()->getTerminator();
9934 bool CannotRemove = false;
9935 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00009936 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009937 CannotRemove = true;
9938 break;
9939 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009940 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9941 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9942 // If there is a stackrestore below this one, remove this one.
9943 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9944 return EraseInstFromFunction(CI);
9945 // Otherwise, ignore the intrinsic.
9946 } else {
9947 // If we found a non-intrinsic call, we can't remove the stack
9948 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009949 CannotRemove = true;
9950 break;
9951 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009952 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009953 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009954
9955 // If the stack restore is in a return/unwind block and if there are no
9956 // allocas or calls between the restore and the return, nuke the restore.
9957 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9958 return EraseInstFromFunction(CI);
9959 break;
9960 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009961 }
9962
Chris Lattner8b0ea312006-01-13 20:11:04 +00009963 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009964}
9965
9966// InvokeInst simplification
9967//
9968Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009969 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009970}
9971
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009972/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9973/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009974static bool isSafeToEliminateVarargsCast(const CallSite CS,
9975 const CastInst * const CI,
9976 const TargetData * const TD,
9977 const int ix) {
9978 if (!CI->isLosslessCast())
9979 return false;
9980
9981 // The size of ByVal arguments is derived from the type, so we
9982 // can't change to a type with a different size. If the size were
9983 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009984 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009985 return true;
9986
9987 const Type* SrcTy =
9988 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9989 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9990 if (!SrcTy->isSized() || !DstTy->isSized())
9991 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009992 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009993 return false;
9994 return true;
9995}
9996
Chris Lattnera44d8a22003-10-07 22:32:43 +00009997// visitCallSite - Improvements for call and invoke instructions.
9998//
9999Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010000 bool Changed = false;
10001
10002 // If the callee is a constexpr cast of a function, attempt to move the cast
10003 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010004 if (transformConstExprCastCall(CS)) return 0;
10005
Chris Lattner6c266db2003-10-07 22:54:13 +000010006 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010007
Chris Lattner08b22ec2005-05-13 07:09:09 +000010008 if (Function *CalleeF = dyn_cast<Function>(Callee))
10009 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10010 Instruction *OldCall = CS.getInstruction();
10011 // If the call and callee calling conventions don't match, this call must
10012 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010013 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010014 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Andersond672ecb2009-07-03 00:17:18 +000010015 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +000010016 // If OldCall dues not return void then replaceAllUsesWith undef.
10017 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010018 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010019 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010020 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10021 return EraseInstFromFunction(*OldCall);
10022 return 0;
10023 }
10024
Chris Lattner17be6352004-10-18 02:59:09 +000010025 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10026 // This instruction is not reachable, just remove it. We insert a store to
10027 // undef so that we know that this code is not reachable, despite the fact
10028 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010029 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010030 UndefValue::get(Type::getInt1PtrTy(*Context)),
Chris Lattner17be6352004-10-18 02:59:09 +000010031 CS.getInstruction());
10032
Devang Patel228ebd02009-10-13 22:56:32 +000010033 // If CS dues not return void then replaceAllUsesWith undef.
10034 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010035 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010036 CS.getInstruction()->
10037 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010038
10039 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10040 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010041 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010042 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010043 }
Chris Lattner17be6352004-10-18 02:59:09 +000010044 return EraseInstFromFunction(*CS.getInstruction());
10045 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010046
Duncan Sandscdb6d922007-09-17 10:26:40 +000010047 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10048 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10049 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10050 return transformCallThroughTrampoline(CS);
10051
Chris Lattner6c266db2003-10-07 22:54:13 +000010052 const PointerType *PTy = cast<PointerType>(Callee->getType());
10053 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10054 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010055 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010056 // See if we can optimize any arguments passed through the varargs area of
10057 // the call.
10058 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010059 E = CS.arg_end(); I != E; ++I, ++ix) {
10060 CastInst *CI = dyn_cast<CastInst>(*I);
10061 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10062 *I = CI->getOperand(0);
10063 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010064 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010065 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010066 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010067
Duncan Sandsf0c33542007-12-19 21:13:37 +000010068 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010069 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010070 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010071 Changed = true;
10072 }
10073
Chris Lattner6c266db2003-10-07 22:54:13 +000010074 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010075}
10076
Chris Lattner9fe38862003-06-19 17:00:31 +000010077// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10078// attempt to move the cast to the arguments of the call/invoke.
10079//
10080bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10081 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10082 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010083 if (CE->getOpcode() != Instruction::BitCast ||
10084 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010085 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010086 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010087 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010088 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010089
10090 // Okay, this is a cast from a function to a different type. Unless doing so
10091 // would cause a type conversion of one of our arguments, change this call to
10092 // be a direct call with arguments casted to the appropriate types.
10093 //
10094 const FunctionType *FT = Callee->getFunctionType();
10095 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010096 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010097
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010098 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010099 return false; // TODO: Handle multiple return values.
10100
Chris Lattnerf78616b2004-01-14 06:06:08 +000010101 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010102 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010103 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010104 // Conversion is ok if changing from one pointer type to another or from
10105 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010106 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010107 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010108 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010109 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010110 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010111
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010112 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010113 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +000010114 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010115 return false; // Cannot transform this return value.
10116
Chris Lattner58d74912008-03-12 17:45:29 +000010117 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010118 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010119 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010120 return false; // Attribute not compatible with transformed value.
10121 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010122
Chris Lattnerf78616b2004-01-14 06:06:08 +000010123 // If the callsite is an invoke instruction, and the return value is used by
10124 // a PHI node in a successor, we cannot change the return type of the call
10125 // because there is no place to put the cast instruction (without breaking
10126 // the critical edge). Bail out in this case.
10127 if (!Caller->use_empty())
10128 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10129 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10130 UI != E; ++UI)
10131 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10132 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010133 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010134 return false;
10135 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010136
10137 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10138 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010139
Chris Lattner9fe38862003-06-19 17:00:31 +000010140 CallSite::arg_iterator AI = CS.arg_begin();
10141 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10142 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010143 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010144
10145 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010146 return false; // Cannot transform this parameter value.
10147
Devang Patel19c87462008-09-26 22:53:05 +000010148 if (CallerPAL.getParamAttributes(i + 1)
10149 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010150 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010151
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010152 // Converting from one pointer type to another or between a pointer and an
10153 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010154 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010155 (TD && ((isa<PointerType>(ParamTy) ||
10156 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10157 (isa<PointerType>(ActTy) ||
10158 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010159 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010160 }
10161
10162 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010163 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010164 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010165
Chris Lattner58d74912008-03-12 17:45:29 +000010166 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10167 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010168 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010169 // won't be dropping them. Check that these extra arguments have attributes
10170 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010171 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10172 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010173 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010174 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010175 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010176 return false;
10177 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010178
Chris Lattner9fe38862003-06-19 17:00:31 +000010179 // Okay, we decided that this is a safe thing to do: go ahead and start
10180 // inserting cast instructions as necessary...
10181 std::vector<Value*> Args;
10182 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010183 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010184 attrVec.reserve(NumCommonArgs);
10185
10186 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010187 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010188
10189 // If the return value is not being used, the type may not be compatible
10190 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010191 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010192
10193 // Add the new return attributes.
10194 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010195 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010196
10197 AI = CS.arg_begin();
10198 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10199 const Type *ParamTy = FT->getParamType(i);
10200 if ((*AI)->getType() == ParamTy) {
10201 Args.push_back(*AI);
10202 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010203 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010204 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010205 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010206 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010207
10208 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010209 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010210 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010211 }
10212
10213 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010214 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010215 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010216 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010217
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010218 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010219 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010220 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010221 errs() << "WARNING: While resolving call to function '"
10222 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010223 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010224 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010225 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10226 const Type *PTy = getPromotedType((*AI)->getType());
10227 if (PTy != (*AI)->getType()) {
10228 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010229 Instruction::CastOps opcode =
10230 CastInst::getCastOpcode(*AI, false, PTy, false);
10231 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010232 } else {
10233 Args.push_back(*AI);
10234 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010235
Duncan Sandse1e520f2008-01-13 08:02:44 +000010236 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010237 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010238 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010239 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010240 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010241 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010242
Devang Patel19c87462008-09-26 22:53:05 +000010243 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10244 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10245
Devang Patel9674d152009-10-14 17:29:00 +000010246 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +000010247 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010248
Eric Christophera66297a2009-07-25 02:45:27 +000010249 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10250 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010251
Chris Lattner9fe38862003-06-19 17:00:31 +000010252 Instruction *NC;
10253 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010254 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010255 Args.begin(), Args.end(),
10256 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010257 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010258 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010259 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010260 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10261 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010262 CallInst *CI = cast<CallInst>(Caller);
10263 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010264 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010265 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010266 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010267 }
10268
Chris Lattner6934a042007-02-11 01:23:03 +000010269 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010270 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010271 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +000010272 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010273 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010274 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010275 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010276
10277 // If this is an invoke instruction, we should insert it after the first
10278 // non-phi, instruction in the normal successor block.
10279 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010280 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010281 InsertNewInstBefore(NC, *I);
10282 } else {
10283 // Otherwise, it's a call, just insert cast right after the call instr
10284 InsertNewInstBefore(NC, *Caller);
10285 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010286 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010287 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010288 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010289 }
10290 }
10291
Devang Patel1bf5ebc2009-10-13 21:41:20 +000010292
Chris Lattner931f8f32009-08-31 05:17:58 +000010293 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010294 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010295
10296 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010297 return true;
10298}
10299
Duncan Sandscdb6d922007-09-17 10:26:40 +000010300// transformCallThroughTrampoline - Turn a call to a function created by the
10301// init_trampoline intrinsic into a direct call to the underlying function.
10302//
10303Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10304 Value *Callee = CS.getCalledValue();
10305 const PointerType *PTy = cast<PointerType>(Callee->getType());
10306 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010307 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010308
10309 // If the call already has the 'nest' attribute somewhere then give up -
10310 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010311 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010312 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010313
10314 IntrinsicInst *Tramp =
10315 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10316
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010317 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010318 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10319 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10320
Devang Patel05988662008-09-25 21:00:45 +000010321 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010322 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010323 unsigned NestIdx = 1;
10324 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010325 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010326
10327 // Look for a parameter marked with the 'nest' attribute.
10328 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10329 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010330 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010331 // Record the parameter type and any other attributes.
10332 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010333 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010334 break;
10335 }
10336
10337 if (NestTy) {
10338 Instruction *Caller = CS.getInstruction();
10339 std::vector<Value*> NewArgs;
10340 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10341
Devang Patel05988662008-09-25 21:00:45 +000010342 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010343 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010344
Duncan Sandscdb6d922007-09-17 10:26:40 +000010345 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010346 // mean appending it. Likewise for attributes.
10347
Devang Patel19c87462008-09-26 22:53:05 +000010348 // Add any result attributes.
10349 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010350 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010351
Duncan Sandscdb6d922007-09-17 10:26:40 +000010352 {
10353 unsigned Idx = 1;
10354 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10355 do {
10356 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010357 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010358 Value *NestVal = Tramp->getOperand(3);
10359 if (NestVal->getType() != NestTy)
10360 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10361 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010362 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010363 }
10364
10365 if (I == E)
10366 break;
10367
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010368 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010369 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010370 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010371 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010372 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010373
10374 ++Idx, ++I;
10375 } while (1);
10376 }
10377
Devang Patel19c87462008-09-26 22:53:05 +000010378 // Add any function attributes.
10379 if (Attributes Attr = Attrs.getFnAttributes())
10380 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10381
Duncan Sandscdb6d922007-09-17 10:26:40 +000010382 // The trampoline may have been bitcast to a bogus type (FTy).
10383 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010384 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010385
Duncan Sandscdb6d922007-09-17 10:26:40 +000010386 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010387 NewTypes.reserve(FTy->getNumParams()+1);
10388
Duncan Sandscdb6d922007-09-17 10:26:40 +000010389 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010390 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010391 {
10392 unsigned Idx = 1;
10393 FunctionType::param_iterator I = FTy->param_begin(),
10394 E = FTy->param_end();
10395
10396 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010397 if (Idx == NestIdx)
10398 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010399 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010400
10401 if (I == E)
10402 break;
10403
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010404 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010405 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010406
10407 ++Idx, ++I;
10408 } while (1);
10409 }
10410
10411 // Replace the trampoline call with a direct call. Let the generic
10412 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010413 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010414 FTy->isVarArg());
10415 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010416 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010417 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010418 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010419 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10420 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010421
10422 Instruction *NewCaller;
10423 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010424 NewCaller = InvokeInst::Create(NewCallee,
10425 II->getNormalDest(), II->getUnwindDest(),
10426 NewArgs.begin(), NewArgs.end(),
10427 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010428 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010429 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010430 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010431 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10432 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010433 if (cast<CallInst>(Caller)->isTailCall())
10434 cast<CallInst>(NewCaller)->setTailCall();
10435 cast<CallInst>(NewCaller)->
10436 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010437 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010438 }
Devang Patel9674d152009-10-14 17:29:00 +000010439 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010440 Caller->replaceAllUsesWith(NewCaller);
10441 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010442 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010443 return 0;
10444 }
10445 }
10446
10447 // Replace the trampoline call with a direct call. Since there is no 'nest'
10448 // parameter, there is no need to adjust the argument list. Let the generic
10449 // code sort out any function type mismatches.
10450 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010451 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010452 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010453 CS.setCalledFunction(NewCallee);
10454 return CS.getInstruction();
10455}
10456
Dan Gohman9ad29202009-09-16 16:50:24 +000010457/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10458/// and if a/b/c and the add's all have a single use, turn this into a phi
Chris Lattner7da52b22006-11-01 04:51:18 +000010459/// and a single binop.
10460Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10461 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010462 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010463 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010464 Value *LHSVal = FirstInst->getOperand(0);
10465 Value *RHSVal = FirstInst->getOperand(1);
10466
10467 const Type *LHSType = LHSVal->getType();
10468 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010469
Dan Gohman9ad29202009-09-16 16:50:24 +000010470 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010471 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010472 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010473 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010474 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010475 // types or GEP's with different index types.
10476 I->getOperand(0)->getType() != LHSType ||
10477 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010478 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010479
10480 // If they are CmpInst instructions, check their predicates
10481 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10482 if (cast<CmpInst>(I)->getPredicate() !=
10483 cast<CmpInst>(FirstInst)->getPredicate())
10484 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010485
10486 // Keep track of which operand needs a phi node.
10487 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10488 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010489 }
Dan Gohman9ad29202009-09-16 16:50:24 +000010490
10491 // If both LHS and RHS would need a PHI, don't do this transformation,
10492 // because it would increase the number of PHIs entering the block,
10493 // which leads to higher register pressure. This is especially
10494 // bad when the PHIs are in the header of a loop.
10495 if (!LHSVal && !RHSVal)
10496 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010497
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010498 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010499
Chris Lattner7da52b22006-11-01 04:51:18 +000010500 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010501 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010502 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010503 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010504 NewLHS = PHINode::Create(LHSType,
10505 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010506 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10507 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010508 InsertNewInstBefore(NewLHS, PN);
10509 LHSVal = NewLHS;
10510 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010511
10512 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010513 NewRHS = PHINode::Create(RHSType,
10514 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010515 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10516 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010517 InsertNewInstBefore(NewRHS, PN);
10518 RHSVal = NewRHS;
10519 }
10520
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010521 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010522 if (NewLHS || NewRHS) {
10523 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10524 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10525 if (NewLHS) {
10526 Value *NewInLHS = InInst->getOperand(0);
10527 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10528 }
10529 if (NewRHS) {
10530 Value *NewInRHS = InInst->getOperand(1);
10531 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10532 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010533 }
10534 }
10535
Chris Lattner7da52b22006-11-01 04:51:18 +000010536 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010537 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010538 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010539 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010540 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010541}
10542
Chris Lattner05f18922008-12-01 02:34:36 +000010543Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10544 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10545
10546 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10547 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010548 // This is true if all GEP bases are allocas and if all indices into them are
10549 // constants.
10550 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010551
10552 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000010553 // more than one phi, which leads to higher register pressure. This is
10554 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010555 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000010556
Dan Gohman9ad29202009-09-16 16:50:24 +000010557 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010558 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10559 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10560 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10561 GEP->getNumOperands() != FirstInst->getNumOperands())
10562 return 0;
10563
Chris Lattner36d3e322009-02-21 00:46:50 +000010564 // Keep track of whether or not all GEPs are of alloca pointers.
10565 if (AllBasePointersAreAllocas &&
10566 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10567 !GEP->hasAllConstantIndices()))
10568 AllBasePointersAreAllocas = false;
10569
Chris Lattner05f18922008-12-01 02:34:36 +000010570 // Compare the operand lists.
10571 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10572 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10573 continue;
10574
10575 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10576 // if one of the PHIs has a constant for the index. The index may be
10577 // substantially cheaper to compute for the constants, so making it a
10578 // variable index could pessimize the path. This also handles the case
10579 // for struct indices, which must always be constant.
10580 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10581 isa<ConstantInt>(GEP->getOperand(op)))
10582 return 0;
10583
10584 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10585 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010586
10587 // If we already needed a PHI for an earlier operand, and another operand
10588 // also requires a PHI, we'd be introducing more PHIs than we're
10589 // eliminating, which increases register pressure on entry to the PHI's
10590 // block.
10591 if (NeededPhi)
10592 return 0;
10593
Chris Lattner05f18922008-12-01 02:34:36 +000010594 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010595 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010596 }
10597 }
10598
Chris Lattner36d3e322009-02-21 00:46:50 +000010599 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010600 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010601 // offset calculation, but all the predecessors will have to materialize the
10602 // stack address into a register anyway. We'd actually rather *clone* the
10603 // load up into the predecessors so that we have a load of a gep of an alloca,
10604 // which can usually all be folded into the load.
10605 if (AllBasePointersAreAllocas)
10606 return 0;
10607
Chris Lattner05f18922008-12-01 02:34:36 +000010608 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10609 // that is variable.
10610 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10611
10612 bool HasAnyPHIs = false;
10613 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10614 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10615 Value *FirstOp = FirstInst->getOperand(i);
10616 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10617 FirstOp->getName()+".pn");
10618 InsertNewInstBefore(NewPN, PN);
10619
10620 NewPN->reserveOperandSpace(e);
10621 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10622 OperandPhis[i] = NewPN;
10623 FixedOperands[i] = NewPN;
10624 HasAnyPHIs = true;
10625 }
10626
10627
10628 // Add all operands to the new PHIs.
10629 if (HasAnyPHIs) {
10630 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10631 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10632 BasicBlock *InBB = PN.getIncomingBlock(i);
10633
10634 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10635 if (PHINode *OpPhi = OperandPhis[op])
10636 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10637 }
10638 }
10639
10640 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010641 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10642 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10643 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010644 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10645 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000010646}
10647
10648
Chris Lattner21550882009-02-23 05:56:17 +000010649/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10650/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010651/// obvious the value of the load is not changed from the point of the load to
10652/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010653///
10654/// Finally, it is safe, but not profitable, to sink a load targetting a
10655/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10656/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010657static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010658 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10659
10660 for (++BBI; BBI != E; ++BBI)
10661 if (BBI->mayWriteToMemory())
10662 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010663
10664 // Check for non-address taken alloca. If not address-taken already, it isn't
10665 // profitable to do this xform.
10666 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10667 bool isAddressTaken = false;
10668 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10669 UI != E; ++UI) {
10670 if (isa<LoadInst>(UI)) continue;
10671 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10672 // If storing TO the alloca, then the address isn't taken.
10673 if (SI->getOperand(1) == AI) continue;
10674 }
10675 isAddressTaken = true;
10676 break;
10677 }
10678
Chris Lattner36d3e322009-02-21 00:46:50 +000010679 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010680 return false;
10681 }
10682
Chris Lattner36d3e322009-02-21 00:46:50 +000010683 // If this load is a load from a GEP with a constant offset from an alloca,
10684 // then we don't want to sink it. In its present form, it will be
10685 // load [constant stack offset]. Sinking it will cause us to have to
10686 // materialize the stack addresses in each predecessor in a register only to
10687 // do a shared load from register in the successor.
10688 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10689 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10690 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10691 return false;
10692
Chris Lattner76c73142006-11-01 07:13:54 +000010693 return true;
10694}
10695
Chris Lattner9fe38862003-06-19 17:00:31 +000010696
Chris Lattnerbac32862004-11-14 19:13:23 +000010697// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10698// operator and they all are only used by the PHI, PHI together their
10699// inputs, and do the operation once, to the result of the PHI.
10700Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10701 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10702
10703 // Scan the instruction, looking for input operations that can be folded away.
10704 // If all input operands to the phi are the same instruction (e.g. a cast from
10705 // the same type or "+42") we can pull the operation through the PHI, reducing
10706 // code size and simplifying code.
10707 Constant *ConstantOp = 0;
10708 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010709 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010710 if (isa<CastInst>(FirstInst)) {
10711 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010712 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010713 // Can fold binop, compare or shift here if the RHS is a constant,
10714 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010715 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010716 if (ConstantOp == 0)
10717 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010718 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10719 isVolatile = LI->isVolatile();
10720 // We can't sink the load if the loaded value could be modified between the
10721 // load and the PHI.
10722 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010723 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010724 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010725
10726 // If the PHI is of volatile loads and the load block has multiple
10727 // successors, sinking it would remove a load of the volatile value from
10728 // the path through the other successor.
10729 if (isVolatile &&
10730 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10731 return 0;
10732
Chris Lattner9c080502006-11-01 07:43:41 +000010733 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010734 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010735 } else {
10736 return 0; // Cannot fold this operation.
10737 }
10738
10739 // Check to see if all arguments are the same operation.
10740 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10741 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10742 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010743 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010744 return 0;
10745 if (CastSrcTy) {
10746 if (I->getOperand(0)->getType() != CastSrcTy)
10747 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010748 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010749 // We can't sink the load if the loaded value could be modified between
10750 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010751 if (LI->isVolatile() != isVolatile ||
10752 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010753 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010754 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010755
Chris Lattner71042962008-07-08 17:18:32 +000010756 // If the PHI is of volatile loads and the load block has multiple
10757 // successors, sinking it would remove a load of the volatile value from
10758 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010759 if (isVolatile &&
10760 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10761 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010762
Chris Lattnerbac32862004-11-14 19:13:23 +000010763 } else if (I->getOperand(1) != ConstantOp) {
10764 return 0;
10765 }
10766 }
10767
10768 // Okay, they are all the same operation. Create a new PHI node of the
10769 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010770 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10771 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010772 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010773
10774 Value *InVal = FirstInst->getOperand(0);
10775 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010776
10777 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010778 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10779 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10780 if (NewInVal != InVal)
10781 InVal = 0;
10782 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10783 }
10784
10785 Value *PhiVal;
10786 if (InVal) {
10787 // The new PHI unions all of the same values together. This is really
10788 // common, so we handle it intelligently here for compile-time speed.
10789 PhiVal = InVal;
10790 delete NewPN;
10791 } else {
10792 InsertNewInstBefore(NewPN, PN);
10793 PhiVal = NewPN;
10794 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010795
Chris Lattnerbac32862004-11-14 19:13:23 +000010796 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010797 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010798 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010799 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010800 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010801 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010802 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010803 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010804 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10805
10806 // If this was a volatile load that we are merging, make sure to loop through
10807 // and mark all the input loads as non-volatile. If we don't do this, we will
10808 // insert a new volatile load and the old ones will not be deletable.
10809 if (isVolatile)
10810 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10811 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10812
10813 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010814}
Chris Lattnera1be5662002-05-02 17:06:02 +000010815
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010816/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10817/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010818static bool DeadPHICycle(PHINode *PN,
10819 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010820 if (PN->use_empty()) return true;
10821 if (!PN->hasOneUse()) return false;
10822
10823 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010824 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010825 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010826
10827 // Don't scan crazily complex things.
10828 if (PotentiallyDeadPHIs.size() == 16)
10829 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010830
10831 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10832 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010833
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010834 return false;
10835}
10836
Chris Lattnercf5008a2007-11-06 21:52:06 +000010837/// PHIsEqualValue - Return true if this phi node is always equal to
10838/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10839/// z = some value; x = phi (y, z); y = phi (x, z)
10840static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10841 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10842 // See if we already saw this PHI node.
10843 if (!ValueEqualPHIs.insert(PN))
10844 return true;
10845
10846 // Don't scan crazily complex things.
10847 if (ValueEqualPHIs.size() == 16)
10848 return false;
10849
10850 // Scan the operands to see if they are either phi nodes or are equal to
10851 // the value.
10852 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10853 Value *Op = PN->getIncomingValue(i);
10854 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10855 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10856 return false;
10857 } else if (Op != NonPhiInVal)
10858 return false;
10859 }
10860
10861 return true;
10862}
10863
10864
Chris Lattner473945d2002-05-06 18:06:38 +000010865// PHINode simplification
10866//
Chris Lattner7e708292002-06-25 16:13:24 +000010867Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010868 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010869 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010870
Owen Anderson7e057142006-07-10 22:03:18 +000010871 if (Value *V = PN.hasConstantValue())
10872 return ReplaceInstUsesWith(PN, V);
10873
Owen Anderson7e057142006-07-10 22:03:18 +000010874 // If all PHI operands are the same operation, pull them through the PHI,
10875 // reducing code size.
10876 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010877 isa<Instruction>(PN.getIncomingValue(1)) &&
10878 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10879 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10880 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10881 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010882 PN.getIncomingValue(0)->hasOneUse())
10883 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10884 return Result;
10885
10886 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10887 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10888 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010889 if (PN.hasOneUse()) {
10890 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10891 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010892 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010893 PotentiallyDeadPHIs.insert(&PN);
10894 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010895 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010896 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010897
10898 // If this phi has a single use, and if that use just computes a value for
10899 // the next iteration of a loop, delete the phi. This occurs with unused
10900 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10901 // common case here is good because the only other things that catch this
10902 // are induction variable analysis (sometimes) and ADCE, which is only run
10903 // late.
10904 if (PHIUser->hasOneUse() &&
10905 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10906 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010907 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010908 }
10909 }
Owen Anderson7e057142006-07-10 22:03:18 +000010910
Chris Lattnercf5008a2007-11-06 21:52:06 +000010911 // We sometimes end up with phi cycles that non-obviously end up being the
10912 // same value, for example:
10913 // z = some value; x = phi (y, z); y = phi (x, z)
10914 // where the phi nodes don't necessarily need to be in the same block. Do a
10915 // quick check to see if the PHI node only contains a single non-phi value, if
10916 // so, scan to see if the phi cycle is actually equal to that value.
10917 {
10918 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10919 // Scan for the first non-phi operand.
10920 while (InValNo != NumOperandVals &&
10921 isa<PHINode>(PN.getIncomingValue(InValNo)))
10922 ++InValNo;
10923
10924 if (InValNo != NumOperandVals) {
10925 Value *NonPhiInVal = PN.getOperand(InValNo);
10926
10927 // Scan the rest of the operands to see if there are any conflicts, if so
10928 // there is no need to recursively scan other phis.
10929 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10930 Value *OpVal = PN.getIncomingValue(InValNo);
10931 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10932 break;
10933 }
10934
10935 // If we scanned over all operands, then we have one unique value plus
10936 // phi values. Scan PHI nodes to see if they all merge in each other or
10937 // the value.
10938 if (InValNo == NumOperandVals) {
10939 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10940 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10941 return ReplaceInstUsesWith(PN, NonPhiInVal);
10942 }
10943 }
10944 }
Chris Lattner60921c92003-12-19 05:58:40 +000010945 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010946}
10947
Chris Lattner7e708292002-06-25 16:13:24 +000010948Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010949 Value *PtrOp = GEP.getOperand(0);
Chris Lattner963f4ba2009-08-30 20:36:46 +000010950 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010951 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010952 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010953
Chris Lattnere87597f2004-10-16 18:11:37 +000010954 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010955 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010956
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010957 bool HasZeroPointerIndex = false;
10958 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10959 HasZeroPointerIndex = C->isNullValue();
10960
10961 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010962 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010963
Chris Lattner28977af2004-04-05 01:30:19 +000010964 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000010965 if (TD) {
10966 bool MadeChange = false;
10967 unsigned PtrSize = TD->getPointerSizeInBits();
10968
10969 gep_type_iterator GTI = gep_type_begin(GEP);
10970 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10971 I != E; ++I, ++GTI) {
10972 if (!isa<SequentialType>(*GTI)) continue;
10973
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010974 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000010975 // to what we need. If narrower, sign-extend it to what we need. This
10976 // explicit cast can make subsequent optimizations more obvious.
10977 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000010978 if (OpBits == PtrSize)
10979 continue;
10980
Chris Lattner2345d1d2009-08-30 20:01:10 +000010981 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010982 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000010983 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000010984 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010985 }
Chris Lattner28977af2004-04-05 01:30:19 +000010986
Chris Lattner90ac28c2002-08-02 19:29:35 +000010987 // Combine Indices - If the source pointer to this getelementptr instruction
10988 // is a getelementptr instruction, combine the indices of the two
10989 // getelementptr instructions into a single instruction.
10990 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010991 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000010992 // Note that if our source is a gep chain itself that we wait for that
10993 // chain to be resolved before we perform this transformation. This
10994 // avoids us creating a TON of code in some cases.
10995 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010996 if (GetElementPtrInst *SrcGEP =
10997 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10998 if (SrcGEP->getNumOperands() == 2)
10999 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000011000
Chris Lattner72588fc2007-02-15 22:48:32 +000011001 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011002
11003 // Find out whether the last index in the source GEP is a sequential idx.
11004 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000011005 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11006 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011007 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011008
Chris Lattner90ac28c2002-08-02 19:29:35 +000011009 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011010 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011011 // Replace: gep (gep %P, long B), long A, ...
11012 // With: T = long A+B; gep %P, T, ...
11013 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011014 Value *Sum;
11015 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11016 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000011017 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011018 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000011019 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011020 Sum = SO1;
11021 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000011022 // If they aren't the same type, then the input hasn't been processed
11023 // by the loop above yet (which canonicalizes sequential index types to
11024 // intptr_t). Just avoid transforming this until the input has been
11025 // normalized.
11026 if (SO1->getType() != GO1->getType())
11027 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011028 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000011029 }
Chris Lattner620ce142004-05-07 22:09:22 +000011030
Chris Lattnerab984842009-08-30 05:30:55 +000011031 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011032 if (Src->getNumOperands() == 2) {
11033 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000011034 GEP.setOperand(1, Sum);
11035 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000011036 }
Chris Lattnerab984842009-08-30 05:30:55 +000011037 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011038 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000011039 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000011040 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011041 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011042 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011043 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000011044 Indices.append(Src->op_begin()+1, Src->op_end());
11045 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011046 }
11047
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011048 if (!Indices.empty())
11049 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11050 Src->isInBounds()) ?
11051 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11052 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011053 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000011054 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000011055 }
11056
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011057 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11058 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011059 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000011060
Chris Lattner2de23192009-08-30 20:38:21 +000011061 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11062 // want to change the gep until the bitcasts are eliminated.
11063 if (getBitCastOperand(X)) {
11064 Worklist.AddValue(PtrOp);
11065 return 0;
11066 }
11067
Chris Lattner963f4ba2009-08-30 20:36:46 +000011068 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11069 // into : GEP [10 x i8]* X, i32 0, ...
11070 //
11071 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11072 // into : GEP i8* X, ...
11073 //
11074 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000011075 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000011076 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11077 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011078 if (const ArrayType *CATy =
11079 dyn_cast<ArrayType>(CPTy->getElementType())) {
11080 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11081 if (CATy->getElementType() == XTy->getElementType()) {
11082 // -> GEP i8* X, ...
11083 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011084 return cast<GEPOperator>(&GEP)->isInBounds() ?
11085 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11086 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011087 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11088 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000011089 }
11090
11091 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011092 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011093 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011094 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011095 // At this point, we know that the cast source type is a pointer
11096 // to an array of the same type as the destination pointer
11097 // array. Because the array type is never stepped over (there
11098 // is a leading zero) we can fold the cast into this GEP.
11099 GEP.setOperand(0, X);
11100 return &GEP;
11101 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011102 }
11103 }
Chris Lattnereed48272005-09-13 00:40:14 +000011104 } else if (GEP.getNumOperands() == 2) {
11105 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011106 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11107 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011108 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11109 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011110 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011111 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11112 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011113 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011114 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011115 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011116 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11117 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011118 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011119 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011120 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011121 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011122
11123 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011124 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011125 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011126 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011127
Owen Anderson1d0be152009-08-13 21:58:54 +000011128 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011129 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011130 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011131
11132 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11133 // allow either a mul, shift, or constant here.
11134 Value *NewIdx = 0;
11135 ConstantInt *Scale = 0;
11136 if (ArrayEltSize == 1) {
11137 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011138 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011139 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011140 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011141 Scale = CI;
11142 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11143 if (Inst->getOpcode() == Instruction::Shl &&
11144 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011145 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11146 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011147 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011148 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011149 NewIdx = Inst->getOperand(0);
11150 } else if (Inst->getOpcode() == Instruction::Mul &&
11151 isa<ConstantInt>(Inst->getOperand(1))) {
11152 Scale = cast<ConstantInt>(Inst->getOperand(1));
11153 NewIdx = Inst->getOperand(0);
11154 }
11155 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011156
Chris Lattner7835cdd2005-09-13 18:36:04 +000011157 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011158 // out, perform the transformation. Note, we don't know whether Scale is
11159 // signed or not. We'll use unsigned version of division/modulo
11160 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011161 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011162 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011163 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011164 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011165 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011166 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11167 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011168 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011169 }
11170
11171 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011172 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011173 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011174 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011175 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11176 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11177 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011178 // The NewGEP must be pointer typed, so must the old one -> BitCast
11179 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011180 }
11181 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011182 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011183 }
Chris Lattner58407792009-01-09 04:53:57 +000011184
Chris Lattner46cd5a12009-01-09 05:44:56 +000011185 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011186 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011187 /// Y = gep X, <...constant indices...>
11188 /// into a gep of the original struct. This is important for SROA and alias
11189 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011190 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011191 if (TD &&
11192 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011193 // Determine how much the GEP moves the pointer. We are guaranteed to get
11194 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011195 ConstantInt *OffsetV =
11196 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011197 int64_t Offset = OffsetV->getSExtValue();
11198
11199 // If this GEP instruction doesn't move the pointer, just replace the GEP
11200 // with a bitcast of the real input to the dest type.
11201 if (Offset == 0) {
11202 // If the bitcast is of an allocation, and the allocation will be
11203 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +000011204 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +000011205 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011206 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11207 if (Instruction *I = visitBitCast(*BCI)) {
11208 if (I != BCI) {
11209 I->takeName(BCI);
11210 BCI->getParent()->getInstList().insert(BCI, I);
11211 ReplaceInstUsesWith(*BCI, I);
11212 }
11213 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011214 }
Chris Lattner58407792009-01-09 04:53:57 +000011215 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011216 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011217 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011218
11219 // Otherwise, if the offset is non-zero, we need to find out if there is a
11220 // field at Offset in 'A's type. If so, we can pull the cast through the
11221 // GEP.
11222 SmallVector<Value*, 8> NewIndices;
11223 const Type *InTy =
11224 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011225 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011226 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11227 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11228 NewIndices.end()) :
11229 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11230 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011231
11232 if (NGEP->getType() == GEP.getType())
11233 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011234 NGEP->takeName(&GEP);
11235 return new BitCastInst(NGEP, GEP.getType());
11236 }
Chris Lattner58407792009-01-09 04:53:57 +000011237 }
11238 }
11239
Chris Lattner8a2a3112001-12-14 16:52:21 +000011240 return 0;
11241}
11242
Victor Hernandez7b929da2009-10-23 21:09:37 +000011243Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattner0864acf2002-11-04 16:18:53 +000011244 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011245 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011246 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11247 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011248 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandeza276c602009-10-17 01:18:07 +000011249 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandez7b929da2009-10-23 21:09:37 +000011250 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011251 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011252
Chris Lattner0864acf2002-11-04 16:18:53 +000011253 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011254 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011255 //
11256 BasicBlock::iterator It = New;
Victor Hernandez7b929da2009-10-23 21:09:37 +000011257 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011258
11259 // Now that I is pointing to the first non-allocation-inst in the block,
11260 // insert our getelementptr instruction...
11261 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011262 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011263 Value *Idx[2];
11264 Idx[0] = NullIdx;
11265 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011266 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11267 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011268
11269 // Now make everything use the getelementptr instead of the original
11270 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011271 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011272 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011273 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011274 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011275 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011276
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011277 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011278 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011279 // Note that we only do this for alloca's, because malloc should allocate
11280 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011281 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011282 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011283
11284 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11285 if (AI.getAlignment() == 0)
11286 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11287 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011288
Chris Lattner0864acf2002-11-04 16:18:53 +000011289 return 0;
11290}
11291
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011292Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11293 Value *Op = FI.getOperand(0);
11294
Chris Lattner17be6352004-10-18 02:59:09 +000011295 // free undef -> unreachable.
11296 if (isa<UndefValue>(Op)) {
11297 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011298 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000011299 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011300 return EraseInstFromFunction(FI);
11301 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011302
Chris Lattner6160e852004-02-28 04:57:37 +000011303 // If we have 'free null' delete the instruction. This can happen in stl code
11304 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011305 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011306 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011307
11308 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11309 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11310 FI.setOperand(0, CI->getOperand(0));
11311 return &FI;
11312 }
11313
11314 // Change free (gep X, 0,0,0,0) into free(X)
11315 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11316 if (GEPI->hasAllZeroIndices()) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000011317 Worklist.Add(GEPI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011318 FI.setOperand(0, GEPI->getOperand(0));
11319 return &FI;
11320 }
11321 }
11322
Victor Hernandez83d63912009-09-18 22:35:49 +000011323 if (isMalloc(Op)) {
11324 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11325 if (Op->hasOneUse() && CI->hasOneUse()) {
11326 EraseInstFromFunction(FI);
11327 EraseInstFromFunction(*CI);
11328 return EraseInstFromFunction(*cast<Instruction>(Op));
11329 }
11330 } else {
11331 // Op is a call to malloc
11332 if (Op->hasOneUse()) {
11333 EraseInstFromFunction(FI);
11334 return EraseInstFromFunction(*cast<Instruction>(Op));
11335 }
11336 }
11337 }
Chris Lattner6160e852004-02-28 04:57:37 +000011338
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011339 return 0;
11340}
11341
Victor Hernandez66284e02009-10-24 04:23:03 +000011342Instruction *InstCombiner::visitFree(Instruction &FI) {
11343 Value *Op = FI.getOperand(1);
11344
11345 // free undef -> unreachable.
11346 if (isa<UndefValue>(Op)) {
11347 // Insert a new store to null because we cannot modify the CFG here.
11348 new StoreInst(ConstantInt::getTrue(*Context),
11349 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11350 return EraseInstFromFunction(FI);
11351 }
11352
11353 // If we have 'free null' delete the instruction. This can happen in stl code
11354 // when lots of inlining happens.
11355 if (isa<ConstantPointerNull>(Op))
11356 return EraseInstFromFunction(FI);
11357
11358 // FIXME: Bring back free (gep X, 0,0,0,0) into free(X) transform
11359
11360 if (isMalloc(Op)) {
11361 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11362 if (Op->hasOneUse() && CI->hasOneUse()) {
11363 EraseInstFromFunction(FI);
11364 EraseInstFromFunction(*CI);
11365 return EraseInstFromFunction(*cast<Instruction>(Op));
11366 }
11367 } else {
11368 // Op is a call to malloc
11369 if (Op->hasOneUse()) {
11370 EraseInstFromFunction(FI);
11371 return EraseInstFromFunction(*cast<Instruction>(Op));
11372 }
11373 }
11374 }
11375
11376 return 0;
11377}
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011378
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011379/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011380static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011381 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011382 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011383 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011384 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011385
Mon P Wang6753f952009-02-07 22:19:29 +000011386 const PointerType *DestTy = cast<PointerType>(CI->getType());
11387 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011388 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011389
11390 // If the address spaces don't match, don't eliminate the cast.
11391 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11392 return 0;
11393
Chris Lattnerb89e0712004-07-13 01:49:43 +000011394 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011395
Reid Spencer42230162007-01-22 05:51:25 +000011396 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011397 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011398 // If the source is an array, the code below will not succeed. Check to
11399 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11400 // constants.
11401 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11402 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11403 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011404 Value *Idxs[2];
Chris Lattnere00c43f2009-10-22 06:44:07 +000011405 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11406 Idxs[1] = Idxs[0];
Owen Andersonbaf3c402009-07-29 18:55:55 +000011407 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011408 SrcTy = cast<PointerType>(CastOp->getType());
11409 SrcPTy = SrcTy->getElementType();
11410 }
11411
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011412 if (IC.getTargetData() &&
11413 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011414 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011415 // Do not allow turning this into a load of an integer, which is then
11416 // casted to a pointer, this pessimizes pointer analysis a lot.
11417 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011418 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11419 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011420
Chris Lattnerf9527852005-01-31 04:50:46 +000011421 // Okay, we are casting from one integer or pointer type to another of
11422 // the same size. Instead of casting the pointer before the load, cast
11423 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011424 Value *NewLoad =
11425 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011426 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011427 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011428 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011429 }
11430 }
11431 return 0;
11432}
11433
Chris Lattner833b8a42003-06-26 05:06:25 +000011434Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11435 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011436
Dan Gohman9941f742007-07-20 16:34:21 +000011437 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011438 if (TD) {
11439 unsigned KnownAlign =
11440 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11441 if (KnownAlign >
11442 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11443 LI.getAlignment()))
11444 LI.setAlignment(KnownAlign);
11445 }
Dan Gohman9941f742007-07-20 16:34:21 +000011446
Chris Lattner963f4ba2009-08-30 20:36:46 +000011447 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011448 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011449 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011450 return Res;
11451
11452 // None of the following transforms are legal for volatile loads.
11453 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011454
Dan Gohman2276a7b2008-10-15 23:19:35 +000011455 // Do really simple store-to-load forwarding and load CSE, to catch cases
11456 // where there are several consequtive memory accesses to the same location,
11457 // separated by a few arithmetic operations.
11458 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011459 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11460 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011461
Chris Lattner878e4942009-10-22 06:25:11 +000011462 // load(gep null, ...) -> unreachable
Christopher Lambb15147e2007-12-29 07:56:53 +000011463 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11464 const Value *GEPI0 = GEPI->getOperand(0);
11465 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011466 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000011467 // Insert a new store to null instruction before the load to indicate
11468 // that this code is not reachable. We do this instead of inserting
11469 // an unreachable instruction directly because we cannot modify the
11470 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011471 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011472 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011473 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011474 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011475 }
Chris Lattner37366c12005-05-01 04:24:53 +000011476
Chris Lattner878e4942009-10-22 06:25:11 +000011477 // load null/undef -> unreachable
11478 // TODO: Consider a target hook for valid address spaces for this xform.
11479 if (isa<UndefValue>(Op) ||
11480 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
11481 // Insert a new store to null instruction before the load to indicate that
11482 // this code is not reachable. We do this instead of inserting an
11483 // unreachable instruction directly because we cannot modify the CFG.
11484 new StoreInst(UndefValue::get(LI.getType()),
11485 Constant::getNullValue(Op->getType()), &LI);
11486 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011487 }
Chris Lattner878e4942009-10-22 06:25:11 +000011488
11489 // Instcombine load (constantexpr_cast global) -> cast (load global)
11490 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
11491 if (CE->isCast())
11492 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11493 return Res;
11494
Chris Lattner37366c12005-05-01 04:24:53 +000011495 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011496 // Change select and PHI nodes to select values instead of addresses: this
11497 // helps alias analysis out a lot, allows many others simplifications, and
11498 // exposes redundancy in the code.
11499 //
11500 // Note that we cannot do the transformation unless we know that the
11501 // introduced loads cannot trap! Something like this is valid as long as
11502 // the condition is always false: load (select bool %C, int* null, int* %G),
11503 // but it would not be valid if we transformed it to load from null
11504 // unconditionally.
11505 //
11506 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11507 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011508 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11509 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011510 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11511 SI->getOperand(1)->getName()+".val");
11512 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11513 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011514 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011515 }
11516
Chris Lattner684fe212004-09-23 15:46:00 +000011517 // load (select (cond, null, P)) -> load P
11518 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11519 if (C->isNullValue()) {
11520 LI.setOperand(0, SI->getOperand(2));
11521 return &LI;
11522 }
11523
11524 // load (select (cond, P, null)) -> load P
11525 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11526 if (C->isNullValue()) {
11527 LI.setOperand(0, SI->getOperand(1));
11528 return &LI;
11529 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011530 }
11531 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011532 return 0;
11533}
11534
Reid Spencer55af2b52007-01-19 21:20:31 +000011535/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011536/// when possible. This makes it generally easy to do alias analysis and/or
11537/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011538static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11539 User *CI = cast<User>(SI.getOperand(1));
11540 Value *CastOp = CI->getOperand(0);
11541
11542 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011543 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11544 if (SrcTy == 0) return 0;
11545
11546 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011547
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011548 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11549 return 0;
11550
Chris Lattner3914f722009-01-24 01:00:13 +000011551 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11552 /// to its first element. This allows us to handle things like:
11553 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11554 /// on 32-bit hosts.
11555 SmallVector<Value*, 4> NewGEPIndices;
11556
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011557 // If the source is an array, the code below will not succeed. Check to
11558 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11559 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011560 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11561 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011562 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011563 NewGEPIndices.push_back(Zero);
11564
11565 while (1) {
11566 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011567 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011568 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011569 NewGEPIndices.push_back(Zero);
11570 SrcPTy = STy->getElementType(0);
11571 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11572 NewGEPIndices.push_back(Zero);
11573 SrcPTy = ATy->getElementType();
11574 } else {
11575 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011576 }
Chris Lattner3914f722009-01-24 01:00:13 +000011577 }
11578
Owen Andersondebcb012009-07-29 22:17:13 +000011579 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011580 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011581
11582 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11583 return 0;
11584
Chris Lattner71759c42009-01-16 20:12:52 +000011585 // If the pointers point into different address spaces or if they point to
11586 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011587 if (!IC.getTargetData() ||
11588 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011589 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011590 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11591 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011592 return 0;
11593
11594 // Okay, we are casting from one integer or pointer type to another of
11595 // the same size. Instead of casting the pointer before
11596 // the store, cast the value to be stored.
11597 Value *NewCast;
11598 Value *SIOp0 = SI.getOperand(0);
11599 Instruction::CastOps opcode = Instruction::BitCast;
11600 const Type* CastSrcTy = SIOp0->getType();
11601 const Type* CastDstTy = SrcPTy;
11602 if (isa<PointerType>(CastDstTy)) {
11603 if (CastSrcTy->isInteger())
11604 opcode = Instruction::IntToPtr;
11605 } else if (isa<IntegerType>(CastDstTy)) {
11606 if (isa<PointerType>(SIOp0->getType()))
11607 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011608 }
Chris Lattner3914f722009-01-24 01:00:13 +000011609
11610 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11611 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011612 if (!NewGEPIndices.empty())
11613 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11614 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000011615
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011616 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11617 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011618 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011619}
11620
Chris Lattner4aebaee2008-11-27 08:56:30 +000011621/// equivalentAddressValues - Test if A and B will obviously have the same
11622/// value. This includes recognizing that %t0 and %t1 will have the same
11623/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011624/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011625/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011626/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011627/// %t2 = load i32* %t1
11628///
11629static bool equivalentAddressValues(Value *A, Value *B) {
11630 // Test if the values are trivially equivalent.
11631 if (A == B) return true;
11632
11633 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011634 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11635 // its only used to compare two uses within the same basic block, which
11636 // means that they'll always either have the same value or one of them
11637 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011638 if (isa<BinaryOperator>(A) ||
11639 isa<CastInst>(A) ||
11640 isa<PHINode>(A) ||
11641 isa<GetElementPtrInst>(A))
11642 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011643 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011644 return true;
11645
11646 // Otherwise they may not be equivalent.
11647 return false;
11648}
11649
Dale Johannesen4945c652009-03-03 21:26:39 +000011650// If this instruction has two uses, one of which is a llvm.dbg.declare,
11651// return the llvm.dbg.declare.
11652DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11653 if (!V->hasNUses(2))
11654 return 0;
11655 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11656 UI != E; ++UI) {
11657 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11658 return DI;
11659 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11660 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11661 return DI;
11662 }
11663 }
11664 return 0;
11665}
11666
Chris Lattner2f503e62005-01-31 05:36:43 +000011667Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11668 Value *Val = SI.getOperand(0);
11669 Value *Ptr = SI.getOperand(1);
11670
11671 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011672 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011673 ++NumCombined;
11674 return 0;
11675 }
Chris Lattner836692d2007-01-15 06:51:56 +000011676
11677 // If the RHS is an alloca with a single use, zapify the store, making the
11678 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011679 // If the RHS is an alloca with a two uses, the other one being a
11680 // llvm.dbg.declare, zapify the store and the declare, making the
11681 // alloca dead. We must do this to prevent declare's from affecting
11682 // codegen.
11683 if (!SI.isVolatile()) {
11684 if (Ptr->hasOneUse()) {
11685 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011686 EraseInstFromFunction(SI);
11687 ++NumCombined;
11688 return 0;
11689 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011690 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11691 if (isa<AllocaInst>(GEP->getOperand(0))) {
11692 if (GEP->getOperand(0)->hasOneUse()) {
11693 EraseInstFromFunction(SI);
11694 ++NumCombined;
11695 return 0;
11696 }
11697 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11698 EraseInstFromFunction(*DI);
11699 EraseInstFromFunction(SI);
11700 ++NumCombined;
11701 return 0;
11702 }
11703 }
11704 }
11705 }
11706 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11707 EraseInstFromFunction(*DI);
11708 EraseInstFromFunction(SI);
11709 ++NumCombined;
11710 return 0;
11711 }
Chris Lattner836692d2007-01-15 06:51:56 +000011712 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011713
Dan Gohman9941f742007-07-20 16:34:21 +000011714 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011715 if (TD) {
11716 unsigned KnownAlign =
11717 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11718 if (KnownAlign >
11719 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11720 SI.getAlignment()))
11721 SI.setAlignment(KnownAlign);
11722 }
Dan Gohman9941f742007-07-20 16:34:21 +000011723
Dale Johannesenacb51a32009-03-03 01:43:03 +000011724 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011725 // stores to the same location, separated by a few arithmetic operations. This
11726 // situation often occurs with bitfield accesses.
11727 BasicBlock::iterator BBI = &SI;
11728 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11729 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011730 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011731 // Don't count debug info directives, lest they affect codegen,
11732 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11733 // It is necessary for correctness to skip those that feed into a
11734 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011735 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011736 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011737 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011738 continue;
11739 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011740
11741 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11742 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011743 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11744 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011745 ++NumDeadStore;
11746 ++BBI;
11747 EraseInstFromFunction(*PrevSI);
11748 continue;
11749 }
11750 break;
11751 }
11752
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011753 // If this is a load, we have to stop. However, if the loaded value is from
11754 // the pointer we're loading and is producing the pointer we're storing,
11755 // then *this* store is dead (X = load P; store X -> P).
11756 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011757 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11758 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011759 EraseInstFromFunction(SI);
11760 ++NumCombined;
11761 return 0;
11762 }
11763 // Otherwise, this is a load from some other location. Stores before it
11764 // may not be dead.
11765 break;
11766 }
11767
Chris Lattner9ca96412006-02-08 03:25:32 +000011768 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011769 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011770 break;
11771 }
11772
11773
11774 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011775
11776 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000011777 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011778 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011779 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011780 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000011781 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011782 ++NumCombined;
11783 }
11784 return 0; // Do not modify these!
11785 }
11786
11787 // store undef, Ptr -> noop
11788 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011789 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011790 ++NumCombined;
11791 return 0;
11792 }
11793
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011794 // If the pointer destination is a cast, see if we can fold the cast into the
11795 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011796 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011797 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11798 return Res;
11799 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011800 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011801 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11802 return Res;
11803
Chris Lattner408902b2005-09-12 23:23:25 +000011804
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011805 // If this store is the last instruction in the basic block (possibly
11806 // excepting debug info instructions and the pointer bitcasts that feed
11807 // into them), and if the block ends with an unconditional branch, try
11808 // to move it to the successor block.
11809 BBI = &SI;
11810 do {
11811 ++BBI;
11812 } while (isa<DbgInfoIntrinsic>(BBI) ||
11813 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011814 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011815 if (BI->isUnconditional())
11816 if (SimplifyStoreAtEndOfBlock(SI))
11817 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011818
Chris Lattner2f503e62005-01-31 05:36:43 +000011819 return 0;
11820}
11821
Chris Lattner3284d1f2007-04-15 00:07:55 +000011822/// SimplifyStoreAtEndOfBlock - Turn things like:
11823/// if () { *P = v1; } else { *P = v2 }
11824/// into a phi node with a store in the successor.
11825///
Chris Lattner31755a02007-04-15 01:02:18 +000011826/// Simplify things like:
11827/// *P = v1; if () { *P = v2; }
11828/// into a phi node with a store in the successor.
11829///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011830bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11831 BasicBlock *StoreBB = SI.getParent();
11832
11833 // Check to see if the successor block has exactly two incoming edges. If
11834 // so, see if the other predecessor contains a store to the same location.
11835 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011836 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011837
11838 // Determine whether Dest has exactly two predecessors and, if so, compute
11839 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011840 pred_iterator PI = pred_begin(DestBB);
11841 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011842 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011843 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011844 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011845 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011846 return false;
11847
11848 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011849 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011850 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011851 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011852 }
Chris Lattner31755a02007-04-15 01:02:18 +000011853 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011854 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011855
11856 // Bail out if all the relevant blocks aren't distinct (this can happen,
11857 // for example, if SI is in an infinite loop)
11858 if (StoreBB == DestBB || OtherBB == DestBB)
11859 return false;
11860
Chris Lattner31755a02007-04-15 01:02:18 +000011861 // Verify that the other block ends in a branch and is not otherwise empty.
11862 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011863 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011864 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011865 return false;
11866
Chris Lattner31755a02007-04-15 01:02:18 +000011867 // If the other block ends in an unconditional branch, check for the 'if then
11868 // else' case. there is an instruction before the branch.
11869 StoreInst *OtherStore = 0;
11870 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011871 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011872 // Skip over debugging info.
11873 while (isa<DbgInfoIntrinsic>(BBI) ||
11874 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11875 if (BBI==OtherBB->begin())
11876 return false;
11877 --BBI;
11878 }
11879 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011880 OtherStore = dyn_cast<StoreInst>(BBI);
11881 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11882 return false;
11883 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011884 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011885 // destinations is StoreBB, then we have the if/then case.
11886 if (OtherBr->getSuccessor(0) != StoreBB &&
11887 OtherBr->getSuccessor(1) != StoreBB)
11888 return false;
11889
11890 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011891 // if/then triangle. See if there is a store to the same ptr as SI that
11892 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011893 for (;; --BBI) {
11894 // Check to see if we find the matching store.
11895 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11896 if (OtherStore->getOperand(1) != SI.getOperand(1))
11897 return false;
11898 break;
11899 }
Eli Friedman6903a242008-06-13 22:02:12 +000011900 // If we find something that may be using or overwriting the stored
11901 // value, or if we run out of instructions, we can't do the xform.
11902 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011903 BBI == OtherBB->begin())
11904 return false;
11905 }
11906
11907 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011908 // make sure nothing reads or overwrites the stored value in
11909 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011910 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11911 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011912 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011913 return false;
11914 }
11915 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011916
Chris Lattner31755a02007-04-15 01:02:18 +000011917 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011918 Value *MergedVal = OtherStore->getOperand(0);
11919 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011920 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011921 PN->reserveOperandSpace(2);
11922 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011923 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11924 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011925 }
11926
11927 // Advance to a place where it is safe to insert the new store and
11928 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011929 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011930 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11931 OtherStore->isVolatile()), *BBI);
11932
11933 // Nuke the old stores.
11934 EraseInstFromFunction(SI);
11935 EraseInstFromFunction(*OtherStore);
11936 ++NumCombined;
11937 return true;
11938}
11939
Chris Lattner2f503e62005-01-31 05:36:43 +000011940
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011941Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11942 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011943 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011944 BasicBlock *TrueDest;
11945 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000011946 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011947 !isa<Constant>(X)) {
11948 // Swap Destinations and condition...
11949 BI.setCondition(X);
11950 BI.setSuccessor(0, FalseDest);
11951 BI.setSuccessor(1, TrueDest);
11952 return &BI;
11953 }
11954
Reid Spencere4d87aa2006-12-23 06:05:41 +000011955 // Cannonicalize fcmp_one -> fcmp_oeq
11956 FCmpInst::Predicate FPred; Value *Y;
11957 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011958 TrueDest, FalseDest)) &&
11959 BI.getCondition()->hasOneUse())
11960 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11961 FPred == FCmpInst::FCMP_OGE) {
11962 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11963 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11964
11965 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000011966 BI.setSuccessor(0, FalseDest);
11967 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011968 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011969 return &BI;
11970 }
11971
11972 // Cannonicalize icmp_ne -> icmp_eq
11973 ICmpInst::Predicate IPred;
11974 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011975 TrueDest, FalseDest)) &&
11976 BI.getCondition()->hasOneUse())
11977 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11978 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11979 IPred == ICmpInst::ICMP_SGE) {
11980 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11981 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11982 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000011983 BI.setSuccessor(0, FalseDest);
11984 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011985 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000011986 return &BI;
11987 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011988
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011989 return 0;
11990}
Chris Lattner0864acf2002-11-04 16:18:53 +000011991
Chris Lattner46238a62004-07-03 00:26:11 +000011992Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11993 Value *Cond = SI.getCondition();
11994 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11995 if (I->getOpcode() == Instruction::Add)
11996 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11997 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11998 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000011999 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012000 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012001 AddRHS));
12002 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000012003 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012004 return &SI;
12005 }
12006 }
12007 return 0;
12008}
12009
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012010Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012011 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012012
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012013 if (!EV.hasIndices())
12014 return ReplaceInstUsesWith(EV, Agg);
12015
12016 if (Constant *C = dyn_cast<Constant>(Agg)) {
12017 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012018 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012019
12020 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012021 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012022
12023 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12024 // Extract the element indexed by the first index out of the constant
12025 Value *V = C->getOperand(*EV.idx_begin());
12026 if (EV.getNumIndices() > 1)
12027 // Extract the remaining indices out of the constant indexed by the
12028 // first index
12029 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12030 else
12031 return ReplaceInstUsesWith(EV, V);
12032 }
12033 return 0; // Can't handle other constants
12034 }
12035 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12036 // We're extracting from an insertvalue instruction, compare the indices
12037 const unsigned *exti, *exte, *insi, *inse;
12038 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12039 exte = EV.idx_end(), inse = IV->idx_end();
12040 exti != exte && insi != inse;
12041 ++exti, ++insi) {
12042 if (*insi != *exti)
12043 // The insert and extract both reference distinctly different elements.
12044 // This means the extract is not influenced by the insert, and we can
12045 // replace the aggregate operand of the extract with the aggregate
12046 // operand of the insert. i.e., replace
12047 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12048 // %E = extractvalue { i32, { i32 } } %I, 0
12049 // with
12050 // %E = extractvalue { i32, { i32 } } %A, 0
12051 return ExtractValueInst::Create(IV->getAggregateOperand(),
12052 EV.idx_begin(), EV.idx_end());
12053 }
12054 if (exti == exte && insi == inse)
12055 // Both iterators are at the end: Index lists are identical. Replace
12056 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12057 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12058 // with "i32 42"
12059 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12060 if (exti == exte) {
12061 // The extract list is a prefix of the insert list. i.e. replace
12062 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12063 // %E = extractvalue { i32, { i32 } } %I, 1
12064 // with
12065 // %X = extractvalue { i32, { i32 } } %A, 1
12066 // %E = insertvalue { i32 } %X, i32 42, 0
12067 // by switching the order of the insert and extract (though the
12068 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012069 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12070 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012071 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12072 insi, inse);
12073 }
12074 if (insi == inse)
12075 // The insert list is a prefix of the extract list
12076 // We can simply remove the common indices from the extract and make it
12077 // operate on the inserted value instead of the insertvalue result.
12078 // i.e., replace
12079 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12080 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12081 // with
12082 // %E extractvalue { i32 } { i32 42 }, 0
12083 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12084 exti, exte);
12085 }
12086 // Can't simplify extracts from other values. Note that nested extracts are
12087 // already simplified implicitely by the above (extract ( extract (insert) )
12088 // will be translated into extract ( insert ( extract ) ) first and then just
12089 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012090 return 0;
12091}
12092
Chris Lattner220b0cf2006-03-05 00:22:33 +000012093/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12094/// is to leave as a vector operation.
12095static bool CheapToScalarize(Value *V, bool isConstant) {
12096 if (isa<ConstantAggregateZero>(V))
12097 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012098 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012099 if (isConstant) return true;
12100 // If all elts are the same, we can extract.
12101 Constant *Op0 = C->getOperand(0);
12102 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12103 if (C->getOperand(i) != Op0)
12104 return false;
12105 return true;
12106 }
12107 Instruction *I = dyn_cast<Instruction>(V);
12108 if (!I) return false;
12109
12110 // Insert element gets simplified to the inserted element or is deleted if
12111 // this is constant idx extract element and its a constant idx insertelt.
12112 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12113 isa<ConstantInt>(I->getOperand(2)))
12114 return true;
12115 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12116 return true;
12117 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12118 if (BO->hasOneUse() &&
12119 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12120 CheapToScalarize(BO->getOperand(1), isConstant)))
12121 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012122 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12123 if (CI->hasOneUse() &&
12124 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12125 CheapToScalarize(CI->getOperand(1), isConstant)))
12126 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012127
12128 return false;
12129}
12130
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012131/// Read and decode a shufflevector mask.
12132///
12133/// It turns undef elements into values that are larger than the number of
12134/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012135static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12136 unsigned NElts = SVI->getType()->getNumElements();
12137 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12138 return std::vector<unsigned>(NElts, 0);
12139 if (isa<UndefValue>(SVI->getOperand(2)))
12140 return std::vector<unsigned>(NElts, 2*NElts);
12141
12142 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012143 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012144 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12145 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012146 Result.push_back(NElts*2); // undef -> 8
12147 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012148 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012149 return Result;
12150}
12151
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012152/// FindScalarElement - Given a vector and an element number, see if the scalar
12153/// value is already around as a register, for example if it were inserted then
12154/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012155static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012156 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012157 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12158 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012159 unsigned Width = PTy->getNumElements();
12160 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012161 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012162
12163 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012164 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012165 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012166 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012167 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012168 return CP->getOperand(EltNo);
12169 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12170 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012171 if (!isa<ConstantInt>(III->getOperand(2)))
12172 return 0;
12173 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012174
12175 // If this is an insert to the element we are looking for, return the
12176 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012177 if (EltNo == IIElt)
12178 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012179
12180 // Otherwise, the insertelement doesn't modify the value, recurse on its
12181 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012182 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012183 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012184 unsigned LHSWidth =
12185 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012186 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012187 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012188 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012189 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012190 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012191 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012192 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012193 }
12194
12195 // Otherwise, we don't know.
12196 return 0;
12197}
12198
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012199Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012200 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012201 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012202 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012203
Dan Gohman07a96762007-07-16 14:29:03 +000012204 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012205 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012206 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012207
Reid Spencer9d6565a2007-02-15 02:26:10 +000012208 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012209 // If vector val is constant with all elements the same, replace EI with
12210 // that element. When the elements are not identical, we cannot replace yet
12211 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012212 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012213 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012214 if (C->getOperand(i) != op0) {
12215 op0 = 0;
12216 break;
12217 }
12218 if (op0)
12219 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012220 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012221
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012222 // If extracting a specified index from the vector, see if we can recursively
12223 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012224 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012225 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012226 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012227
12228 // If this is extracting an invalid index, turn this into undef, to avoid
12229 // crashing the code below.
12230 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012231 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012232
Chris Lattner867b99f2006-10-05 06:55:50 +000012233 // This instruction only demands the single element from the input vector.
12234 // If the input vector has a single use, simplify it based on this use
12235 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012236 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012237 APInt UndefElts(VectorWidth, 0);
12238 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012239 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012240 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012241 EI.setOperand(0, V);
12242 return &EI;
12243 }
12244 }
12245
Owen Andersond672ecb2009-07-03 00:17:18 +000012246 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012247 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012248
12249 // If the this extractelement is directly using a bitcast from a vector of
12250 // the same number of elements, see if we can find the source element from
12251 // it. In this case, we will end up needing to bitcast the scalars.
12252 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12253 if (const VectorType *VT =
12254 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12255 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012256 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12257 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012258 return new BitCastInst(Elt, EI.getType());
12259 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012260 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012261
Chris Lattner73fa49d2006-05-25 22:53:38 +000012262 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000012263 // Push extractelement into predecessor operation if legal and
12264 // profitable to do so
12265 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12266 if (I->hasOneUse() &&
12267 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12268 Value *newEI0 =
12269 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12270 EI.getName()+".lhs");
12271 Value *newEI1 =
12272 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12273 EI.getName()+".rhs");
12274 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012275 }
Chris Lattner275a6d62009-09-08 18:48:01 +000012276 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000012277 // Extracting the inserted element?
12278 if (IE->getOperand(2) == EI.getOperand(1))
12279 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12280 // If the inserted and extracted elements are constants, they must not
12281 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012282 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012283 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012284 EI.setOperand(0, IE->getOperand(0));
12285 return &EI;
12286 }
12287 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12288 // If this is extracting an element from a shufflevector, figure out where
12289 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012290 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12291 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012292 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012293 unsigned LHSWidth =
12294 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12295
12296 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012297 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012298 else if (SrcIdx < LHSWidth*2) {
12299 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012300 Src = SVI->getOperand(1);
12301 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012302 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012303 }
Eric Christophera3500da2009-07-25 02:28:41 +000012304 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012305 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12306 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012307 }
12308 }
Eli Friedman2451a642009-07-18 23:06:53 +000012309 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012310 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012311 return 0;
12312}
12313
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012314/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12315/// elements from either LHS or RHS, return the shuffle mask and true.
12316/// Otherwise, return false.
12317static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012318 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012319 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012320 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12321 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012322 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012323
12324 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012325 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012326 return true;
12327 } else if (V == LHS) {
12328 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012329 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012330 return true;
12331 } else if (V == RHS) {
12332 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012333 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012334 return true;
12335 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12336 // If this is an insert of an extract from some other vector, include it.
12337 Value *VecOp = IEI->getOperand(0);
12338 Value *ScalarOp = IEI->getOperand(1);
12339 Value *IdxOp = IEI->getOperand(2);
12340
Chris Lattnerd929f062006-04-27 21:14:21 +000012341 if (!isa<ConstantInt>(IdxOp))
12342 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012343 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012344
12345 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12346 // Okay, we can handle this if the vector we are insertinting into is
12347 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012348 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012349 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012350 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012351 return true;
12352 }
12353 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12354 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012355 EI->getOperand(0)->getType() == V->getType()) {
12356 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012357 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012358
12359 // This must be extracting from either LHS or RHS.
12360 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12361 // Okay, we can handle this if the vector we are insertinting into is
12362 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012363 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012364 // If so, update the mask to reflect the inserted value.
12365 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012366 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012367 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012368 } else {
12369 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012370 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012371 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012372
12373 }
12374 return true;
12375 }
12376 }
12377 }
12378 }
12379 }
12380 // TODO: Handle shufflevector here!
12381
12382 return false;
12383}
12384
12385/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12386/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12387/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012388static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012389 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012390 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012391 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012392 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012393 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012394
12395 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012396 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012397 return V;
12398 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012399 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012400 return V;
12401 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12402 // If this is an insert of an extract from some other vector, include it.
12403 Value *VecOp = IEI->getOperand(0);
12404 Value *ScalarOp = IEI->getOperand(1);
12405 Value *IdxOp = IEI->getOperand(2);
12406
12407 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12408 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12409 EI->getOperand(0)->getType() == V->getType()) {
12410 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012411 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12412 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012413
12414 // Either the extracted from or inserted into vector must be RHSVec,
12415 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012416 if (EI->getOperand(0) == RHS || RHS == 0) {
12417 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012418 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012419 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012420 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012421 return V;
12422 }
12423
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012424 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012425 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12426 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012427 // Everything but the extracted element is replaced with the RHS.
12428 for (unsigned i = 0; i != NumElts; ++i) {
12429 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012430 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012431 }
12432 return V;
12433 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012434
12435 // If this insertelement is a chain that comes from exactly these two
12436 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012437 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12438 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012439 return EI->getOperand(0);
12440
Chris Lattnerefb47352006-04-15 01:39:45 +000012441 }
12442 }
12443 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012444 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012445
12446 // Otherwise, can't do anything fancy. Return an identity vector.
12447 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012448 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012449 return V;
12450}
12451
12452Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12453 Value *VecOp = IE.getOperand(0);
12454 Value *ScalarOp = IE.getOperand(1);
12455 Value *IdxOp = IE.getOperand(2);
12456
Chris Lattner599ded12007-04-09 01:11:16 +000012457 // Inserting an undef or into an undefined place, remove this.
12458 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12459 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012460
Chris Lattnerefb47352006-04-15 01:39:45 +000012461 // If the inserted element was extracted from some other vector, and if the
12462 // indexes are constant, try to turn this into a shufflevector operation.
12463 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12464 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12465 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012466 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012467 unsigned ExtractedIdx =
12468 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012469 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012470
12471 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12472 return ReplaceInstUsesWith(IE, VecOp);
12473
12474 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012475 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012476
12477 // If we are extracting a value from a vector, then inserting it right
12478 // back into the same place, just use the input vector.
12479 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12480 return ReplaceInstUsesWith(IE, VecOp);
12481
Chris Lattnerefb47352006-04-15 01:39:45 +000012482 // If this insertelement isn't used by some other insertelement, turn it
12483 // (and any insertelements it points to), into one big shuffle.
12484 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12485 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012486 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012487 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012488 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012489 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012490 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012491 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012492 }
12493 }
12494 }
12495
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012496 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12497 APInt UndefElts(VWidth, 0);
12498 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12499 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12500 return &IE;
12501
Chris Lattnerefb47352006-04-15 01:39:45 +000012502 return 0;
12503}
12504
12505
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012506Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12507 Value *LHS = SVI.getOperand(0);
12508 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012509 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012510
12511 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012512
Chris Lattner867b99f2006-10-05 06:55:50 +000012513 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012514 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012515 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012516
Dan Gohman488fbfc2008-09-09 18:11:14 +000012517 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012518
12519 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12520 return 0;
12521
Evan Cheng388df622009-02-03 10:05:09 +000012522 APInt UndefElts(VWidth, 0);
12523 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12524 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012525 LHS = SVI.getOperand(0);
12526 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012527 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012528 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012529
Chris Lattner863bcff2006-05-25 23:48:38 +000012530 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12531 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12532 if (LHS == RHS || isa<UndefValue>(LHS)) {
12533 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012534 // shuffle(undef,undef,mask) -> undef.
12535 return ReplaceInstUsesWith(SVI, LHS);
12536 }
12537
Chris Lattner863bcff2006-05-25 23:48:38 +000012538 // Remap any references to RHS to use LHS.
12539 std::vector<Constant*> Elts;
12540 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012541 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012542 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012543 else {
12544 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012545 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012546 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012547 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012548 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012549 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012550 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012551 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012552 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012553 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012554 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012555 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012556 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012557 LHS = SVI.getOperand(0);
12558 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012559 MadeChange = true;
12560 }
12561
Chris Lattner7b2e27922006-05-26 00:29:06 +000012562 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012563 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012564
Chris Lattner863bcff2006-05-25 23:48:38 +000012565 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12566 if (Mask[i] >= e*2) continue; // Ignore undef values.
12567 // Is this an identity shuffle of the LHS value?
12568 isLHSID &= (Mask[i] == i);
12569
12570 // Is this an identity shuffle of the RHS value?
12571 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012572 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012573
Chris Lattner863bcff2006-05-25 23:48:38 +000012574 // Eliminate identity shuffles.
12575 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12576 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012577
Chris Lattner7b2e27922006-05-26 00:29:06 +000012578 // If the LHS is a shufflevector itself, see if we can combine it with this
12579 // one without producing an unusual shuffle. Here we are really conservative:
12580 // we are absolutely afraid of producing a shuffle mask not in the input
12581 // program, because the code gen may not be smart enough to turn a merged
12582 // shuffle into two specific shuffles: it may produce worse code. As such,
12583 // we only merge two shuffles if the result is one of the two input shuffle
12584 // masks. In this case, merging the shuffles just removes one instruction,
12585 // which we know is safe. This is good for things like turning:
12586 // (splat(splat)) -> splat.
12587 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12588 if (isa<UndefValue>(RHS)) {
12589 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12590
12591 std::vector<unsigned> NewMask;
12592 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12593 if (Mask[i] >= 2*e)
12594 NewMask.push_back(2*e);
12595 else
12596 NewMask.push_back(LHSMask[Mask[i]]);
12597
12598 // If the result mask is equal to the src shuffle or this shuffle mask, do
12599 // the replacement.
12600 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012601 unsigned LHSInNElts =
12602 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012603 std::vector<Constant*> Elts;
12604 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012605 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012606 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012607 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012608 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012609 }
12610 }
12611 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12612 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012613 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012614 }
12615 }
12616 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012617
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012618 return MadeChange ? &SVI : 0;
12619}
12620
12621
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012622
Chris Lattnerea1c4542004-12-08 23:43:58 +000012623
12624/// TryToSinkInstruction - Try to move the specified instruction from its
12625/// current block into the beginning of DestBlock, which can only happen if it's
12626/// safe to move the instruction past all of the instructions between it and the
12627/// end of its block.
12628static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12629 assert(I->hasOneUse() && "Invariants didn't hold!");
12630
Chris Lattner108e9022005-10-27 17:13:11 +000012631 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012632 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012633 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012634
Chris Lattnerea1c4542004-12-08 23:43:58 +000012635 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012636 if (isa<AllocaInst>(I) && I->getParent() ==
12637 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012638 return false;
12639
Chris Lattner96a52a62004-12-09 07:14:34 +000012640 // We can only sink load instructions if there is nothing between the load and
12641 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012642 if (I->mayReadFromMemory()) {
12643 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012644 Scan != E; ++Scan)
12645 if (Scan->mayWriteToMemory())
12646 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012647 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012648
Dan Gohman02dea8b2008-05-23 21:05:58 +000012649 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012650
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012651 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012652 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012653 ++NumSunkInst;
12654 return true;
12655}
12656
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012657
12658/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12659/// all reachable code to the worklist.
12660///
12661/// This has a couple of tricks to make the code faster and more powerful. In
12662/// particular, we constant fold and DCE instructions as we go, to avoid adding
12663/// them to the worklist (this significantly speeds up instcombine on code where
12664/// many instructions are dead or constant). Additionally, if we find a branch
12665/// whose condition is a known constant, we only visit the reachable successors.
12666///
Chris Lattner2ee743b2009-10-15 04:59:28 +000012667static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012668 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012669 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012670 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +000012671 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +000012672 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012673 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +000012674
12675 std::vector<Instruction*> InstrsForInstCombineWorklist;
12676 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012677
Chris Lattner2ee743b2009-10-15 04:59:28 +000012678 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
12679
Chris Lattner2c7718a2007-03-23 19:17:18 +000012680 while (!Worklist.empty()) {
12681 BB = Worklist.back();
12682 Worklist.pop_back();
12683
12684 // We have now visited this block! If we've already been here, ignore it.
12685 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012686
Chris Lattner2c7718a2007-03-23 19:17:18 +000012687 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12688 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012689
Chris Lattner2c7718a2007-03-23 19:17:18 +000012690 // DCE instruction if trivially dead.
12691 if (isInstructionTriviallyDead(Inst)) {
12692 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012693 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012694 Inst->eraseFromParent();
12695 continue;
12696 }
12697
12698 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012699 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
12700 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12701 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12702 << *Inst << '\n');
12703 Inst->replaceAllUsesWith(C);
12704 ++NumConstProp;
12705 Inst->eraseFromParent();
12706 continue;
12707 }
Chris Lattner2ee743b2009-10-15 04:59:28 +000012708
12709
12710
12711 if (TD) {
12712 // See if we can constant fold its operands.
12713 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
12714 i != e; ++i) {
12715 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
12716 if (CE == 0) continue;
12717
12718 // If we already folded this constant, don't try again.
12719 if (!FoldedConstants.insert(CE))
12720 continue;
12721
12722 Constant *NewC =
12723 ConstantFoldConstantExpression(CE, BB->getContext(), TD);
12724 if (NewC && NewC != CE) {
12725 *i = NewC;
12726 MadeIRChange = true;
12727 }
12728 }
12729 }
12730
Devang Patel7fe1dec2008-11-19 18:56:50 +000012731
Chris Lattner67f7d542009-10-12 03:58:40 +000012732 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012733 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012734
12735 // Recursively visit successors. If this is a branch or switch on a
12736 // constant, only visit the reachable successor.
12737 TerminatorInst *TI = BB->getTerminator();
12738 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12739 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12740 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012741 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012742 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012743 continue;
12744 }
12745 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12746 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12747 // See if this is an explicit destination.
12748 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12749 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012750 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012751 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012752 continue;
12753 }
12754
12755 // Otherwise it is the default destination.
12756 Worklist.push_back(SI->getSuccessor(0));
12757 continue;
12758 }
12759 }
12760
12761 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12762 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012763 }
Chris Lattner67f7d542009-10-12 03:58:40 +000012764
12765 // Once we've found all of the instructions to add to instcombine's worklist,
12766 // add them in reverse order. This way instcombine will visit from the top
12767 // of the function down. This jives well with the way that it adds all uses
12768 // of instructions to the worklist after doing a transformation, thus avoiding
12769 // some N^2 behavior in pathological cases.
12770 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
12771 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +000012772
12773 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012774}
12775
Chris Lattnerec9c3582007-03-03 02:04:50 +000012776bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012777 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012778
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012779 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12780 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012781
Chris Lattnerb3d59702005-07-07 20:40:38 +000012782 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012783 // Do a depth-first traversal of the function, populate the worklist with
12784 // the reachable instructions. Ignore blocks that are not reachable. Keep
12785 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012786 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +000012787 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012788
Chris Lattnerb3d59702005-07-07 20:40:38 +000012789 // Do a quick scan over the function. If we find any blocks that are
12790 // unreachable, remove any instructions inside of them. This prevents
12791 // the instcombine code from having to deal with some bad special cases.
12792 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12793 if (!Visited.count(BB)) {
12794 Instruction *Term = BB->getTerminator();
12795 while (Term != BB->begin()) { // Remove instrs bottom-up
12796 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012797
Chris Lattnerbdff5482009-08-23 04:37:46 +000012798 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012799 // A debug intrinsic shouldn't force another iteration if we weren't
12800 // going to do one without it.
12801 if (!isa<DbgInfoIntrinsic>(I)) {
12802 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012803 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000012804 }
Devang Patel228ebd02009-10-13 22:56:32 +000012805
Devang Patel228ebd02009-10-13 22:56:32 +000012806 // If I is not void type then replaceAllUsesWith undef.
12807 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000012808 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000012809 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012810 I->eraseFromParent();
12811 }
12812 }
12813 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012814
Chris Lattner873ff012009-08-30 05:55:36 +000012815 while (!Worklist.isEmpty()) {
12816 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012817 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012818
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012819 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012820 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012821 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000012822 EraseInstFromFunction(*I);
12823 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012824 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012825 continue;
12826 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012827
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012828 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012829 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
12830 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12831 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012832
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012833 // Add operands to the worklist.
12834 ReplaceInstUsesWith(*I, C);
12835 ++NumConstProp;
12836 EraseInstFromFunction(*I);
12837 MadeIRChange = true;
12838 continue;
12839 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012840
Chris Lattnerea1c4542004-12-08 23:43:58 +000012841 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012842 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012843 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +000012844 Instruction *UserInst = cast<Instruction>(I->use_back());
12845 BasicBlock *UserParent;
12846
12847 // Get the block the use occurs in.
12848 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
12849 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
12850 else
12851 UserParent = UserInst->getParent();
12852
Chris Lattnerea1c4542004-12-08 23:43:58 +000012853 if (UserParent != BB) {
12854 bool UserIsSuccessor = false;
12855 // See if the user is one of our successors.
12856 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12857 if (*SI == UserParent) {
12858 UserIsSuccessor = true;
12859 break;
12860 }
12861
12862 // If the user is one of our immediate successors, and if that successor
12863 // only has us as a predecessors (we'd have to split the critical edge
12864 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +000012865 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012866 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012867 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012868 }
12869 }
12870
Chris Lattner74381062009-08-30 07:44:24 +000012871 // Now that we have an instruction, try combining it to simplify it.
12872 Builder->SetInsertPoint(I->getParent(), I);
12873
Reid Spencera9b81012007-03-26 17:44:01 +000012874#ifndef NDEBUG
12875 std::string OrigI;
12876#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000012877 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000012878 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
12879
Chris Lattner90ac28c2002-08-02 19:29:35 +000012880 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012881 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012882 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012883 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012884 DEBUG(errs() << "IC: Old = " << *I << '\n'
12885 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000012886
Chris Lattnerf523d062004-06-09 05:08:07 +000012887 // Everything uses the new instruction now.
12888 I->replaceAllUsesWith(Result);
12889
12890 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000012891 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012892 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012893
Chris Lattner6934a042007-02-11 01:23:03 +000012894 // Move the name to the new instruction first.
12895 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012896
12897 // Insert the new instruction into the basic block...
12898 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012899 BasicBlock::iterator InsertPos = I;
12900
12901 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12902 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12903 ++InsertPos;
12904
12905 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012906
Chris Lattner7a1e9242009-08-30 06:13:40 +000012907 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000012908 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012909#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000012910 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12911 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000012912#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012913
Chris Lattner90ac28c2002-08-02 19:29:35 +000012914 // If the instruction was modified, it's possible that it is now dead.
12915 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012916 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012917 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000012918 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012919 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012920 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012921 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012922 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012923 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012924 }
12925 }
12926
Chris Lattner873ff012009-08-30 05:55:36 +000012927 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012928 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012929}
12930
Chris Lattnerec9c3582007-03-03 02:04:50 +000012931
12932bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012933 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000012934 Context = &F.getContext();
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012935 TD = getAnalysisIfAvailable<TargetData>();
12936
Chris Lattner74381062009-08-30 07:44:24 +000012937
12938 /// Builder - This is an IRBuilder that automatically inserts new
12939 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000012940 IRBuilder<true, TargetFolder, InstCombineIRInserter>
12941 TheBuilder(F.getContext(), TargetFolder(TD, F.getContext()),
Chris Lattner74381062009-08-30 07:44:24 +000012942 InstCombineIRInserter(Worklist));
12943 Builder = &TheBuilder;
12944
Chris Lattnerec9c3582007-03-03 02:04:50 +000012945 bool EverMadeChange = false;
12946
12947 // Iterate while there is work to do.
12948 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012949 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012950 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000012951
12952 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012953 return EverMadeChange;
12954}
12955
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012956FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012957 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012958}